ajax从php接收响应,但不能与ajax一起使用

时间:2018-12-02 18:04:26

标签: php jquery mysql ajax

当我在网络标签中使用ctrl+shift+I签入google chrome时,我具有以下php和ajax代码,它将响应显示为<{"response" : "2"},但无法将该响应分配给<h3>将ID作为respo

我的php是

<<?php

$id = $_POST['reccount'];
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "testsite");
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt update query execution
$sql = "SELECT * FROM paper WHERE ID=$id";
if(mysqli_query($link, $sql)){

$result = mysqli_query($link, $sql);
  while($row = mysqli_fetch_array($result)) {
    $data['response']= $row['response'];
    $data['ansnum'] = $row['q_no'];
}
echo json_encode($data);
} else {
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

// Close connection
mysqli_close($link);
?>

而ajax是

 $.ajax({
        type:"POST",
        url:"<?php echo base_url();?>/shortfiles/loadans.php",
        data: {reccount: reccount},
         dataType:"JSON",
          success: function(data){
          alert (data.response);
           $('#respond').text(data.response);
                          }


                    })  ;

而html是

<h3 ID="respond"style="margin-left:30px;">response</h3>

1 个答案:

答案 0 :(得分:0)

如果您的PHP响应为:

<{"response" : "2"}

这将是格式错误的JSON字符串。这将由文档开头的多余<创建。我建议您使用以下PHP开瓶器:

<?php

这应该可以解决问题,因此JSON响应将是:

{"response" : "2"}

届时它将被正确解析。

示例

<?php
$id = (int)$_POST['reccount'];
$link = mysqli_connect("localhost", "root", "", "testsite");
header('Content-Type: application/json');
if($link === false){
  die("{\"error\": \"Could not connect. " . mysqli_connect_error() . "\"}");
}
$sql = "SELECT * FROM paper WHERE ID=$id";
if(mysqli_query($link, $sql)){
  $result = mysqli_query($link, $sql);
  while($row = mysqli_fetch_array($result)) {
    $data['response']= $row['response'];
    $data['ansnum'] = $row['q_no'];
  }
  echo json_encode($data);
} else {
  echo "{\"error\": \"Unable to execute $sql. " . mysqli_error($link) . "\"}";
}
mysqli_close($link);
?>

在我的示例中,我将POST数据投射到Integer,以帮助确保恶意用户不会发送除数字之外的任何内容。即使发送错误,我也只发送JSON数据。使用header()有助于定义浏览器的数据。

$.ajax({
  type:"POST",
  url:"<?php echo base_url();?>/shortfiles/loadans.php",
  data: {reccount: reccount},
  dataType:"JSON",
  success: function(data){
    console.log(data);
    if(data.error !== undefined){
      alert(data.error);
    } else {
      $('#respond').text(data.response);
    }
  }
});

希望有帮助。