【问题标题】:AJAX with WordPress HTTP API带有 WordPress HTTP API 的 AJAX
【发布时间】:2018-08-08 18:28:26
【问题描述】:

我是 php 的新手,在这里停留在我的轨道上,因此感谢您提供任何帮助。我在 JS 文件中编写了一些函数来渲染和更新我制作的 WordPress 模板的图库视图。在updateGallery() 函数中,我在按下页面上的提交按钮后进行了 AJAX 调用,但收到“解析器错误”。

Arguments(3) [{…}, "parsererror", SyntaxError: Unexpected token A in JSON at position 0 at parse (<anonymous>) at Ut (https://…, callee: ƒ, Symbol(Symbol.iterator): ƒ]

我直接在我的 WP 模板中尝试了 API 请求的代码以呈现响应,它按预期工作,但是当我尝试合并我的脚本时,我得到了错误,我无法弄清楚是什么原因造成的。

JS

function updateGallery() {

    var county = $("#county").val();

    jQuery(".galleryGrid").fadeOut("fast", function() {
        console.log("ajax request");
        jQuery(".galleryGrid").html("").hide();
        $.ajax({
            type : "GET",
            dataType : "JSON",
            url : ajax.url,
            data : { 
                action: "get_gallery_data",
                county_id : county
            },
            error: function(response, error) {
                console.log(arguments);
                alert("Failed because: " + error);
            },
            success : function(response) {
                if(response.type === "success") {
                    console.log("Success")
                    renderGrid(response.data);
                }
            }
        });
    });
}

PHP

add_action("wp_ajax_nopriv_get_gallery_data", "get_gallery_data");
add_action("wp_ajax_get_gallery_data", "get_gallery_data");

function get_gallery_data() {

    $county_id = $_REQUEST[county_id];

    $base_api_url = "https://some.api.com/";

    $filters = array(
        "field" => "field_153",
        "operator" =>"is",
        "value" => $county_id
    );

    $filters_url = rawurlencode(json_encode($filters));

    $api_url = $base_api_url."?filters=".$filters_url;


    $request = wp_remote_get($api_url, array(
        "headers" => array(
            "Application-Id" => "5xxxxxx",
            "REST-API-KEY" => "0xxxxxx",
        ),
    ));

    $body = wp_remote_retrieve_body($request);
    $output = json_decode($body, true);
    echo $output;

    die();
};

【问题讨论】:

  • 要输出 json,请在数组 php.net/manual/en/function.json-encode.php 上使用 json_encode()。如果wp_remote_retrieve_body($request) 返回 json 字符串....只是回显
  • 是的,正如@charlietfl 所说,您需要使用json_encode()
  • @charlietfl 这就是我最初所做的,但没有得到回应。出于某种原因,这是接收响应的唯一方法,尽管会出现错误。
  • 通过将成功回调记录到控制台来检查实际响应。如果没有任何反应,请检查浏览器开发工具网络中的整个请求并查看响应正文以查看其实际包含的内容

标签: php jquery wordpress


【解决方案1】:
 $output = json_decode($body, true);

//改变

 $output = json_encode($body, true);

【讨论】:

    猜你喜欢
    • 2015-09-14
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    相关资源
    最近更新 更多