2016-02-26 55 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"); 
    } 
});