javascript - 在 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。我试图将它传递给另一个函数,但只有那部分数据
解决方案
这是一个使用查询字符串参数的非常简单的内容协商示例...
在你的 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
})
推荐阅读
- ios - 如何通过 WKWebVIew 或 JSC 在 iOS 应用程序中加载 WebAssembly
- python - 如何在 apache livy 中使用 python 脚本提交 jar?
- cmake - 从 makefile 到 Cmake - stm32
- postgresql - 如何从 jsonb 的数组字段中具有 jsonb 嵌套字段的 postgresql 中过滤数据?
- ruby - 无法在 mac 上安装 tiny_tds
- consensus - 在 Ubuntu 16.04 上运行的 Sawtooth 上的 Devmode-engine-rust
- javascript - 我正在使用搜索栏,但我想为其添加预设网址
- java - 用于接口的 Java 类型转换
- google-apps-script - 更改特定单元格时发送电子邮件
- flutter - 如何在颤振应用程序中编辑文本?