如何发送PHP变量并使用Jquery检索它们(没有echo)?
我正在构建一个搜索函数来检索google地图的XML数据 除此之外,我还想显示实际发现了多少结果 我曾考虑在实际文档中进行回显,但这可能会弄乱标记数据。调用成功后,如何获取PHP变量并在Jquery中检索它 如果我的PHP看起来像这样:如何发送PHP变量并使用Jquery检索它们(没有echo)?,php,jquery,Php,Jquery,我正在构建一个搜索函数来检索google地图的XML数据 除此之外,我还想显示实际发现了多少结果 我曾考虑在实际文档中进行回显,但这可能会弄乱标记数据。调用成功后,如何获取PHP变量并在Jquery中检索它 如果我的PHP看起来像这样: $result = mysql_query($query); if (!$result) { die('Invalid query: ' . mysql_error()); } $num_rows = mysql_num_rows($result);
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$num_rows = mysql_num_rows($result);
$.ajax({
type: "POST",
url: "MapSearchxml.php",
data: {
dataFromDate: FromDate,
//lalala
dataHasPatio: HasPatio
},
beforeSend: function (html) { // this happens before actual call
$("#results").html('Please Wait');
$("#searchresults").show();
$(".phpFromDate").html(FromDate);
},
success: function (data, status, jqXHR) {
//Success?
},
dataType: 'xml'
});
Jquery是这样的:
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$num_rows = mysql_num_rows($result);
$.ajax({
type: "POST",
url: "MapSearchxml.php",
data: {
dataFromDate: FromDate,
//lalala
dataHasPatio: HasPatio
},
beforeSend: function (html) { // this happens before actual call
$("#results").html('Please Wait');
$("#searchresults").show();
$(".phpFromDate").html(FromDate);
},
success: function (data, status, jqXHR) {
//Success?
},
dataType: 'xml'
});
只是为您尝试一个JSON示例,它有echo,但您可以用它做复杂的事情 不确定这是否是你的目标?我知道您不想对每个变量执行echo,如果使用JSON,您也不会这样做
<?php
$simple = 'simple string';
$complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
var simple = '<?php echo $simple; ?>';
var complex = <?php echo json_encode($complex); ?>;
</script>
var-simple='';
var复数=;
您可以看到,AJAX获得成功的是html代码。如果您使用AJAX创建了一个完整的html页面,您将获得它,从
开始,到
结束。您可以在返回的html数据上做一个特殊的标记,比如[sepical_info:'info']
或其他什么,然后对其进行过滤。好的,我需要一点时间来解释您的问题,可能我还是错了,让我们试试:
从技术上讲,你想做的事情是不可能的。简而言之:如果执行一个Ajax请求,则返回一个响应。调用success
函数的那一刻,您的PHP脚本就已经不存在了。因此,您只能传递一个返回值
但是,您可以做的是,将该返回值设置为嵌套值,例如,包含两个部分:
由于您没有在这里显示任何代码,因此我无法为您的案例提供一个快速的示例(我将此作为您未来问题的指针)。添加名称空间元素,就像属性在PHP中非常简单一样。可能会发现在PHP中创建数组和发送JSON更容易。At客户端很容易在响应对象/数组上循环
$output=array('status'=>'', 'results'=>array());
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$num_rows = mysql_num_rows($result);
if( $num_rows){
$output['status']='ok';
/* push row data to $output['results'][]; in while loop*/
}else{
$output['status']= 'No results';
}
echo json_encode( $output);
然后在jQuery中:
success:function( data){
if (data.status != 'No results' ){
/* count array length*/
var count= data.results.length;
/* loop over data.results array*/
}
}
/* change dataType to "json"*/
我忘记了
count
并在jQuery中添加了它……还可以将count
属性添加到$output
php数组中,并使用$num\u rows
填充您需要“回显”一些内容。在本例中,它将是组合的XML document.Dump文件,并使用apache的mod x-sendfile-no not really:/Show输出,我建议使用jsonp。