Javascript 在Jquery中获取Ajax返回的值和html标记
我使用以下内容使用Jquery检索一些html: index.phpJavascript 在Jquery中获取Ajax返回的值和html标记,javascript,jquery,Javascript,Jquery,我使用以下内容使用Jquery检索一些html: index.php $.post( 'get-products.php', $("#offerForm").serialize() + '&lastid=' + highest, function(data) { $('#demo').html(data); } $.post( 'get-products.php', $("#offerFor
$.post(
'get-products.php',
$("#offerForm").serialize() + '&lastid=' + highest,
function(data) {
$('#demo').html(data);
}
$.post(
'get-products.php',
$("#offerForm").serialize() + '&lastid=' + highest,
function(data) {
$('#demo').html(data);
//variable processing statement goes here
}
是否也可以从get-products.php检索变量的值,例如:
get-products.php
<? echo $htmlOutput;
echo $variable; ?>
您应该尝试使用JSON进行通信。 通过这种方式,在get-products.php中,您可以返回一个包含html和一些变量的json编码数组 然后在jquery中,您将获得data.variable1、data.variable2等 通过使用第三个参数(“json”)调用post来实现 在get-products.php中返回
echo json_encode(array('html' => '<div>some html</div>', 'variable1'=>xxxx));
echo json_encode(数组('html'=>some html','variable1'=>xxxx));
是的,您可以使用json。例如:
<?php
$html = "<p>some html</p>";
$data = array('key' => 'value');
$output = json_encode(array('html' => $html, 'data'=>$data));
echo $output;
?>
您可以从
get products.php
页面返回JSON,如下所示:
<?
$arr = array('htmlOutput' => $htmlOutput, 'otherVariable' => $variable);
echo json_encode($arr);
?>
问题是您在url上设置了一个本地路径,而js请求在请求中不理解该路径,因为它在您的系统上本地运行
简单地用类似于JSON的url替换“get products.php”是最好的选择,但是如果由于某种原因无法实现此功能,可以在返回的html中的外部元素上设置一个数据属性,然后使用
jQuery.data()
读取它
html
根据您的数据,有几种方法可供选择。它们都基于相同的概念:将数据添加到DOM 您可以返回包含某些值的隐藏输入:
<input id=data-object type=hidden value=myvalue />
这适用于单个小值
您可以将数据添加到相关的DOM元素:
<div id=some-div custom-value=myvalue>
这样,您可以将额外的信息附加到DOM周围的特定元素
您可以在脚本标记中添加Javascript对象,并使用客户端代码访问它:
<script type=text/javascript>
var myData = {attribute: value, someObject:{anotherAttribute: value}};
</script>
var myData={attribute:value,someObject:{anotherAttribute:value};
顺便说一句,参数数据类型不是必需的,但它是安全的。
<div class="response-outer" data-variable-name="value">
...
</div>
$.post(
'get-products.php',
$("#offerForm").serialize() + '&lastid=' + highest,
function(data) {
$('#demo').html(response);
var x = $("#demo").find(".response-outer").data("variable-name");
}
)
<input id=data-object type=hidden value=myvalue />
<div id=some-div custom-value=myvalue>
<script type=text/javascript>
var myData = {attribute: value, someObject:{anotherAttribute: value}};
</script>