使用jQuery发布到WordPress Ajax以获得插件时出现404错误 [英] Getting a 404 error when using jQuery to post to WordPress Ajax for a plugin

查看:210
本文介绍了使用jQuery发布到WordPress Ajax以获得插件时出现404错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个注册的插件来处理ajax调用(注册调用正在运行,我已通过日志记录对其进行了检查).当我使用jQuery发布到它(通过admin-ajax.php)时,它永远不会被调用,并且Wordpress会引发404错误.但是,如果我改为在浏览器http://my-site.com/wp-admin/admin-ajax.php?action=my_ajax_function的地址栏中键入内容,那么它将起作用!

I have a plugin that registers to handle an ajax call (and the registration call is run, I checked it with logging). When I use jQuery to post to it (via admin-ajax.php), it is never called and Wordpress throws a 404 error. But, if I instead type into the address bar of the browser http://my-site.com/wp-admin/admin-ajax.php?action=my_ajax_function then it works!

客户端

jQuery.post(
    {
        url: ajaxurl, //This is correct, I printed it out and it's "/wp-admin/admin-ajax.php"
        data: { action: 'my_ajax_function' },
        success: function(response)
        {
            //Never called
            console.dir( response );
        },
        dataType: "json"
    }
    //This is called
).fail( handleError );

服务器端

//This code IS called in my plugin's "load" hook
add_action( "wp_ajax_my_ajax_function", "handleAjax" );
add_action( "wp_ajax_nopriv_my_ajax_function", "handleAjax" );

//This is never called
public function handleAjax()
{
    echo "{ \"status\": \"ok\"}";
    die();
}

当我直接将表单发布到ajaxurl时,它可以工作!只能通过jQuery抛出404!以下代码可以完美执行:

When I post a form to ajaxurl directly, it works! It's only through jQuery that it throws 404! The below code executes perfectly:

//Posting without JQuery works!
form.method = "POST";
form.action = ajaxurl;
form.submit();

编辑#2:该错误似乎与JQuery有关!

当我直接使用Ajax时(即在我的代码中创建XMLHttpRequest,调用xmlHttpRequest.open(...)等),它可以完美发布!只有JQuery会引发错误!

When I use Ajax directly (i.e. creating XMLHttpRequest in my code, calling xmlHttpRequest.open(...), etc), it posts perfectly! Only JQuery throws the error!

如何确定JQuery中的原因是什么?

How do I find out what in JQuery is causing this?

推荐答案

您误解了 $ .ajax $ .post ,请改用此

jQuery.ajax({
        url: ajaxurl,
        type : 'post',
        data: { action: 'my_ajax_function' },
        success: function(response){
            console.dir( response );
        },
        dataType: "json"
}).fail( handleError );

$.post是类型为 post 的$ .ajax的缩写,具有以下签名

$.post is a short hand of $.ajax for type post, which having following signature

jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

这篇关于使用jQuery发布到WordPress Ajax以获得插件时出现404错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆