ajax die,javascript - Why does Wordpress ajax die('0') - Stack Overflow

在WordPress中,作者遇到一个AJAX回调函数的问题。他们在functions.php文件中添加了send_email_callback函数来处理发送邮件,并通过wp_ajax_和wp_ajax_nopriv_钩子注册。然而,当回调函数返回JSON响应时,JavaScript收到的响应中包含了一个额外的'0'。问题源于admin-ajax.php文件中默认的'die('0')';这导致了JSON解析错误。作者探讨了解决方案,包括修改admin-ajax.php或在send_email_callback函数末尾直接使用'die()'。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I added the following to my functions.php file:

add_action('wp_ajax_send_email', 'send_email_callback');

add_action('wp_ajax_nopriv_send_email', 'send_email_callback');

So i added the following callback function:

send_email_callback()

{

//do some processing

echo json_encode(array('response'=>'Ya man it worked.'));

//return control back to *-ajax.php

}

This is what is returned to my javascript :

{"response":"Ya man it worked."}0

So ofcourse when it reaches the $.parseJSON( msg ) line I get Uncaught SyntaxError: Unexpected number.

var request = $.ajax({

url: "/wp-admin/admin-ajax.php",

method: "POST",

data: { action : 'send_email', P : container },

dataType: "html"

});

request.done(function( msg ) {

var obj = $.parseJSON( msg );

console.log(obj.response);

});

request.fail(function( jqXHR, textStatus ) {

alert( "Request failed: " + textStatus );

});

});

So where does this 0 come from? admin-ajax.php

it says on line 97:

// Default status

die( '0' );

Why is this here, why am I reaching the die('0') line? Shouldnt it be just die() so it doesnt mess up my response?

Seems the only way to fix this is either modify admin-ajax.php or simply die() at the end of my send_email_callback() function.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值