首页 > 解决方案 > 在 AJAX 调用中从 (data) 中提取数组数据

问题描述

这不能回答问题 - jQuery Ajax 返回 html AND json 数据

我不能使用 wrap 方法,因为我没有单个 html 字符串。我没有使用Phery,我在这里尝试了第一个选项,第二个嵌套调用在第一个之前运行,因此数据未定义-jquery 在同一个函数中使用两个完成的回调,一个具有数据类型 json 一个没有 ,我们不使用仅 html5为了这。因此,引用的答案没有解决这个问题。

在我的.done函数中,我有(数据)返回。该数据是 phpecho和单个JSON_encode数组的混合。样本数据:

.....
//other divs and data above this point
<div id="test">text</div>
{"ids":["1","5","2","6"]}0

AJAX

.done(function(data) {
console.log(data);
func2(json_string)
})

我希望能够提取并单独使用数组 {"ids":["1","5","2","6"]}0。我试图将它传递给另一个函数,但只有那部分数据

标签: javascriptjqueryajax

解决方案


这是一个使用查询字符串参数的非常简单的内容协商示例...

在你的 PHP 中,像这样分解你的 HTML 和 JSON 部分

<?php
$format = $_GET["format"] ?? "html";
if ($format === "json") {
    header("Content-type: application/json");
    echo json_encode(["ids" => [1, 5, 2, 6]]);
    exit;
}
?>
.....
//other divs and data above this point
<div id="test">text</div>

然后在您的 JavaScript 代码中,使用

$.ajax(my_ajax.ajax_url, {
  dataType: "html",
  // etc
}).done(html => {
  // html content here
})

$.ajax(`${my_ajax.ajax_url}?format=json`, {
  dataType: "json",
  // etc
}).done(json => {
  // json content here
})

推荐阅读