如何在使用jQuery Ajax方法时接收和处理来自PHP的响应?
javascript
$.ajax({
type: 'post',
url: 'show.php',
data: {name: name},
dataType: 'json',
success: function(response) {
//I want my json response back here
}
});show.php
$hostelName = $_POST['name'];
$sql = //here is the actual sql containing the $hostelname
$query = mysql_query($sql);
$obj = mysql_fetch_object($query);
$sum = $obj->sum;
$tour = $obj->tour;
echo json_encode(
array(
"sum" => $sum,
"tour" => $tour
)
);发布于 2014-01-23 09:29:51
试试这个:
$.ajax({
type: 'post',
url: 'show.php',
data: "name="+ name,
dataType: 'json',
success: function(response) {
//here I'd like back the php query
}您的PHP代码如下:
$hostelName =mysql_escape_string($_POST['name']);
$sql = //here is the actual sql containing the $hostelname
$query = mysql_query($sql);
$reusult = mysql_fetch_assoc($query);
echo json_encode($reusult);发布于 2014-01-23 09:26:07
在PHP代码中,您将以JSON的形式返回响应。所以只需要在下面的代码片段中解析
$.ajax({
type: 'post',
url: 'show.php',
data: {name: name},
dataType: 'json',
success: function(response) {
//response is json you need to parse it
var json = response,
obj = JSON.parse(json);
alert(obj.sum);
alert(obj.tour);
}https://stackoverflow.com/questions/21303955
复制相似问题