2016-02-26 82 views
0

收到JSON我無法從PHP獲得JSON在服務器無法從服務器通過PHP

的JavaScript代碼:

 $.ajax({ 
      type: "POST", 
      url: "doingSQL.php", 
      data: label, 
      success: function(result) { 
       $("#p").html("All my book: <br>"+ result); 
       console.log(result); 
       }, 
      dataType: "json", 
      error: function(xhr){ 
       console.log("error"); 
       } 
     }); 

doingSQL.php的作業從SQL數據庫中選擇BOOKNAME和將數據轉換爲json。它看起來像這樣:

/* the server connecting code is omitted */ 

    if ($_SERVER["REQUEST_METHOD"] == "POST") { 
     $label = $_POST["label"]; 
    } 
      $sql = "SELECT * FROM book WHERE ower = '". $label."'"; 
      $result = mysqli_query($conn, $sql); 

      if (mysqli_num_rows($result) > 0) { 

      // output data of each row 
      while($row = mysqli_fetch_assoc($result)) { 
       $Arr = array("id" => $row["book_id"], 
         "bookName" => $row["bookName"]); 

       $bookDetail[] = array("book".$i => $Arr); 

     }} 


     } 

    mysqli_close($conn); 
    $json = array("mybook" => $bookDetail); 
    echo json_encode($json);// return json 

但我在html控制檯得到的結果是「[]」或數組[0]。

JSON是有效的JSON格式,它看起來像:

{ 
    "mybook":[ 
     { 
     "book0":{ 
      "id":"0", 
      "bookName":"bookA" 
     } 
     }, 
     { 
     "book1":{ 
      "id":"1", 
      "bookName":"bookB" 
     } 
     } 
    ] 
} 

然而,如果代碼是PHP SQL連接。 json返回將成功。 它看起來像:

/* the server connecting code is omitted */ 

mysqli_close($conn); 
// if outside the SQL connection 

$ArrA = array("id" => "0", "bookName" => "bookA"); 
$ArrB = array("id" => "1", "bookName" => "bookB"); 

$bookDetail[] = array("book0" => $ArrA); 
$bookDetail[] = array("book0" => $ArrB); 

$json = array("mybook" => $bookDetail); 
echo json_encode($json);// return json success 

任何想法?

+0

它看起來就像你分配從返回的值您關閉連接後的查詢。 –

+0

另請注意,如果這是生產代碼,您很容易受到[SQL注入](https://en.wikipedia.org/wiki/SQL_injection) – Tserkov

回答

0

只是通過你的Ajax data爲:的PlainObjectStringArray

data: {label:label} 
0

ajax settingsdata屬性可以是類型。欲瞭解更多信息,請參閱此http://api.jquery.com/jquery.ajax

所以你的JavaScript代碼會是這樣的:

$.ajax({ 
    type: "POST", 
    url: "doingSQL.php", 
    data: {label: label}, 
    success: function(result) { 
    $("#p").html("All my book: <br>"+ result); 
    console.log(result); 
    }, 
    dataType: "json", 
    error: function(xhr){ 
    console.log("error"); 
    } 
}); 
+0

爲什麼我的php仍然可以在編輯數據之前獲得標籤值:{ label:label}?例如,我可以使用標籤值在php中進行sql選擇,但不能返回到JavaScript。 –

0

你需要在一個變量傳遞label值。現在,因爲PHP的頁面上使用的是$_POST['label'],所以傳遞變量是這樣的:

data: {label: label}, 

所以你完全AJAX代碼是這樣:

$.ajax({ 
    type: "POST", 
    url: "doingSQL.php", 
    data: {label: label}, // changed here 
    success: function(result) { 
    $("#p").html("All my book: <br>"+ result); 
    console.log(result); 
    }, 
    dataType: "json", 
    error: function(xhr){ 
    console.log("error"); 
    } 
});