我正在使用JQuery AJAX函数将数据传递给PHP文档。
目前,AJAX成功函数返回HTML,并将其添加到html页面。
我的目标是使成功函数返回可用作JavaScript变量的第二个/不同的数据。
如何做到这一点?
更新
问题得到了正确回答。以下是生成的脚本的示例。
PHP文档
<?php
$some_html = 'foo';
$some_value_for_js_variable = 'bar';
// create json content
echo "{";
echo "\"some_html_outupt\":\"$some_html\",";
echo "\"some_value_for_js_varialbe_output\":\"$some_vale_for_js_variable\"";
echo "}";
?>
JS文件
// Jquery ajax function
$.ajax({
dataType: 'json',
type: "POST",
url: "some_file.php", // the location of the above mentioned php script
cache: false,
success: function(json) {
$(el).html(json['some_html_output']); // add html output to page
var a = json['some_value_for_js_varialbe_output']; // assign value to js varialbe
}
}
}); // ajax
答案 0 :(得分:3)
我实现这一点的方法是在JSON字符串中返回数据,其中包含2个项目。第一部分将保存HTML,第二部分保存所需变量的数据。
{"html":{html},
"2nd variable":"{data}"}
然后您可以对您的Web服务器执行$ .getJSON调用,如
$.getJSON('path','querystring=if_needed',function(data){
var html = data['html'];
var 2ndVariable = data['2nd Variable']
//do other things that you want
});
我希望有帮助