2012-02-08 147 views
2
返回的HTML标记相处的值

我用下面的使用来获取一些HTML Jquery的:与阿贾克斯jQuery的

的index.php

$.post(
    'get-products.php', 
    $("#offerForm").serialize() + '&lastid=' + highest, 
    function(data) {    
     $('#demo').html(data); 
    } 

是否有可能也获取的值从GET-products.php变量,例如:

GET-products.php

<? echo $htmlOutput; 
echo $variable; ?> 

的index.php

$.post(
    'get-products.php', 
    $("#offerForm").serialize() + '&lastid=' + highest, 
    function(data) { 
     $('#demo').html(data); 
     //variable processing statement goes here 
    } 

回答

2

您应该尝试使用JSON进行通信。 这样在GET-products.php您可以返回编码包含你的HTML数组JSON,一些变量 然后在jQuery的你会得到data.variable1,data.variable2等..

通过做吧呼叫后用第三个参数( “JSON”) http://api.jquery.com/jQuery.post/

$.post(
     'get-products.php', 
     $("#offerForm").serialize() + '&lastid=' + highest, 
     function(data) {    
      $('#demo').html(data.html); 
      variable1 = data.variable1; 
     } 

而在GET-products.php回报

echo json_encode(array('html' => '<div>some html</div>', 'variable1'=>xxxx)); 
+0

参数数据类型是没有必要的BTW,但它是安全的。 – giorgio 2012-02-08 13:17:52

0

是的,你可以使用JSON了点。例如:

<?php 
$html = "<p>some html</p>"; 
$data = array('key' => 'value'); 
$output = json_encode(array('html' => $html, 'data'=>$data)); 
echo $output; 
?> 

现在jQuery中获取的数据等:

function(data) { 
    $('#demo').html(data.html); 
    // and do something with data.data 
    alert(data.data.key); // alerts "value" 
} 
0

你可以,而不是从你的get-products.php页返回JSON,像这样:

<? 
    $arr = array('htmlOutput' => $htmlOutput, 'otherVariable' => $variable); 
    echo json_encode($arr); 
?> 

的jQuery:

$.post(
    'get-products.php', 
    $("#offerForm").serialize() + '&lastid=' + highest, 
    function(data) { 
     $('#demo').html(data.htmlOutput); 
     var x = data.otherVariable; 
    } 
) 
0

JSON是最好的选择的网址,但如果由于某种原因,你无法实现这一点,您可以设置对数据属性返回html中的外部元素,然后使用jQuery.data()来读取它。

HTML

<div class="response-outer" data-variable-name="value"> 
... 
</div> 

注:该数据属性将由jQuery的自动解析和如果它是在JSON格式将被转换成一个javascript对象

jQuery的

$.post(
    'get-products.php', 
    $("#offerForm").serialize() + '&lastid=' + highest, 
    function(data) { 
     $('#demo').html(response); 
     var x = $("#demo").find(".response-outer").data("variable-name"); 
    } 
) 
0

有有几个选项可以做到这一点,这取决于你的数据。它们都基于相同的概念:将数据添加到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>