我创建了一个jquery ajax请求并尝试将一个变量传递给php来进行查询并将数据返回给实际的上下文。
处理ajax的实际上下文:
$.ajax({
type: 'post',
url: 'show.php',
data: {name: name},
dataType: 'json',
success: function(response) {
//here I'd like back the php query
}
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
)
);
答案 0 :(得分:6)
试试这个:
$.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);
答案 1 :(得分:1)
在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);
}