php 如何使用 jquery ajax 提供和取回数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21303955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to give and get data back with jquery ajax?
提问by Boldizsar
I created a jquery ajax request and trying to pass a variable to the php to do a query and give back data to the actual context.
我创建了一个 jquery ajax 请求,并尝试将一个变量传递给 php 以进行查询并将数据返回给实际上下文。
The actual context, handling the ajax:
处理 ajax 的实际上下文:
$.ajax({
type: 'post',
url: 'show.php',
data: {name: name},
dataType: 'json',
success: function(response) {
//here I'd like back the php query
}
The php:
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
)
);
回答by Karthick Kumar
Try this:
尝试这个:
$.ajax({
type: 'post',
url: 'show.php',
data: "name="+ name,
dataType: 'json',
success: function(response) {
//here I'd like back the php query
}
and your PHP code to this:
和你的 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);
回答by Jason W
In your PHP code you are returning response as JSON. so just need to parse as below in code snippet
在您的 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);
}

