gpt4 book ai didi

javascript - WordPress AJAX 问题

转载 作者:行者123 更新时间:2023-12-03 03:49:48 25 4
gpt4 key购买 nike

我一直在尝试将数组从 PHP 发送到 javascript,以便可以显示数据库中的搜索结果。我已将数组转换为 JSON,但现在似乎无法检索它。我从未使用过 AJAX,但我这里工作的一些人已经使用过,但没有人能够找出确切的问题(假设他们没有花太多时间在这上面)

 $(document).ready( function() {
var data = {};
$.ajax({
type: 'GET',
url: '../wp-content/plugins/advantage-geo/get_data.php',
data: "data",
dataType: 'json',
cache: false,
success: function(result) {
alert(result.d);
console.log(result);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});

这是来自JS文件的调用。 (以}结束);但它没有被纳入代码块,所以我将其删除。)

以下是PHP

<?php 

header("Content-type:json");

global $wpdb;

$sql = "SELECT * FROM wptest_geo_db";
$result = $wpdb->get_results($sql) or die(mysql_error());


echo json_encode($result);

print_r(json_decode($person_array));
print_r($person_array);

?>

JSON 已正确创建,我可以将其显示在 php 文件的页面上。 AJAX 调用抛出 500 内部服务器错误,我不知道为什么。

最佳答案

我的回答可能不会直接谈论 500 服务器错误,但仔细阅读我的回答可能会帮助您解决该问题。

AJAX 调用不需要您以 JSON 形式发送 HTTP 请求类型,因此您只需将编码后的 JSON 作为字符串输出即可。 AJAX 会将其识别为 JSON 数据,您甚至不需要告诉 jQuery AJAX 您需要 JSON 数据,它会识别。

<?php 
// it's not required that the response HTTP request is of type JOSN
// just ignore this
//header("Content-type:json");

global $wpdb;

$sql = "SELECT * FROM wptest_geo_db";
$result = $wpdb->get_results($sql) or die(mysql_error());

echo json_encode($result);

// you've echo-ed the encoded JSON just above
// why would you print the arrays?
// I assume it's for testing purpose
//print_r(json_decode($person_array));
//print_r($person_array);
?>

现在,进入 WordPress AJAX。你这样做是完全错误的。请查看此文档了解如何在 WordPress 中处理 AJAX https://codex.wordpress.org/AJAX_in_Plugins 。测试并试用链接的 AJAX 教程/文档中的内容,如果您在尝试时遇到任何问题,请返回此处。

关于javascript - WordPress AJAX 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45215855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com