2015-01-01 57 views
-1

我是網絡技術領域的新手。我正在努力將數據從PHP服務器發送到客戶端test.html。但只有警報(「1」),但警報(「2」)不打印我只是想打印Json數據到警報(JSON.stringify(response));,請告訴我我錯在哪裏?如何將數據從PHP服務器發送到客戶端

我的服務器代碼是api.php

<?php 
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request 
mysql_connect("localhost","root","1234"); 
mysql_select_db("demo"); 
if(isset($_GET['type'])) 
{ 
    if($_GET['type']=="login"){ 
     $username=$_GET['UserName']; 
     $Password=$_GET['Password']; 
     $query="Select * from registration where UserName='$username' and Password='$Password'"; 
     $result=mysql_query($query); 
     $totalRows=mysql_num_rows($result); 
     if($totalRows>0){ 
      $recipes=array(); 
      while($recipe=mysql_fetch_array($result, MYSQL_ASSOC)){ 
       $recipes[]=array('User'=>$recipe); 
      } 
      $output=json_encode(array('Users'=>$recipes)); 
      echo $output; 
     } 
    } 
} 
else{ 
    echo "Invalid format"; 
} 

我的客戶代碼 的test.html

<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
     <title>JSON </title> 
     <script src="Scripts/jquery-1.8.2.js"> 
     </script> 
     <script> 
      $(document).ready(function(){ 
       alert("1"); 
       $("#btnLogin").click(function(){ 
        alert("2"); 
        $.ajax({ 
         url:"http://localhost/Experiements/webservices/api.php", 
         type:"GET", 
         dataType:"json", 
         data:{type:"login", UserName:"abhishek",Password:"123456"}, 
         ContentType:"application/json", 
         success: function(response){ 
          alert(JSON.stringify(response)); 
         }, 
         error: function(err){ 
          alert(JSON.stringify(err)); 
         } 
        }) 
       }); 
      }); 
     </script> 
    </head> 
    <body> 
     <input type="button" id="btnLogin" name="btnLogin" value="Login"/> 
    </body> 
</html> 

數據庫演示,用戶名是和密碼和表是登記 enter image description here

+0

以上是工作代碼,感謝@Indra Kumar S,我糾正了錯誤,您只需下載jquery-1.8.2.js並保存在腳本文件夾內,然後就可以工作。 – geeks

+0

這個問題似乎有一個[XY問題](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem),標題應該改變,以表明它是關於調試一個特定的實現。不知道如何對它進行描述,而沒有直接提到答案,這表明問題沒有被縮小到問題的範圍之內。 – Anko

回答

3

jQuery中#選擇器用於通過其id不是其name屬性)選擇的元素。所以一個id添加到你的按鈕。

<input type="button" id="btnLogin" name="btnLogin" value="Login"/> 

現在你的$("#btnLogin").click()函數應該工作。

+0

謝謝指出,錯誤 – geeks

2

錯誤1:輸入中缺少id。它添加

<input type="button" id="btnLogin" name="btnLogin" value="Login"/> 

錯誤2: AJAX的URL與PHP的目的,但你在input元提到api.html

url:"http://localhost/Experiements/webservices/api.php", 
+0

謝謝,在我的代碼有錯誤1,但沒有錯誤2,我提到.php不是HTML謝謝 – geeks

+0

但你只提到「我的服務器代碼是api.html」..... api.html和api.php不一樣的權利? –

+0

哦...,我糾正了謝謝 – geeks

0

使用id屬性在javascript與#btnLogin指它

+0

感謝您指出錯誤 – geeks

相關問題