【问题标题】:Using the JQuery Ajax function to Return 2 Sets of Data使用 JQuery Ajax 函数返回 2 组数据
【发布时间】:2009-07-11 14:27:34
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: javascript jquery ajax


    【解决方案1】:

    我实现这一点的方式是返回 JSON 字符串中的数据,其中包含 2 个项目。第一部分将保存 HTML,第二部分将保存所需变量的数据。

    {"html":{html},
    "2nd variable":"{data}"}
    

    然后您可以像这样对您的网络服务器进行 $.getJSON 调用

    $.getJSON('path','querystring=if_needed',function(data){
        var html = data['html'];
        var 2ndVariable = data['2nd Variable']
        //do other things that you want
    });
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多