我有一个jQuery选择的<button>
标记(不包含<form>
),用于向Wordpress中的ajax处理程序提交Ajax POST请求。返回一个错误对象,指示后端未获取任何数据对。我做了一个手动浏览器来获取带有url参数的请求,就像一个测试一样,并且ajax处理程序也起作用了。这是我的html和jQuery代码:
// html button. No form
<button id="previousButton">Previous</button>
// ajax request function
function ajaxPost() {
//
?>
<script>
jQuery(document).ready(function() {
jQuery('#previousButton').click(function() {
var ajaxScript = { ajaxUrl : 'http://localhost/wptest2/wp-admin/admin-ajax.php' };
jQuery.ajax({
type: "POST",
url: ajaxScript.ajaxUrl,
contentType : 'application/x-www-form-urlencoded; charset=UTF-8',
dataType: "json",
data: {
action: "selectTargetsWithOffset",
},
success: function(response) {
console.log(response, `=====success response=====`);
},
error: function(error) {
console.log(error, `=====error=====`);
}
});
});
})
</script>
<?php
}
add_action('admin_footer', 'ajaxPost');
错误对象:
options-general.php?page=fvc-settings:810 {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}abort: ƒ (a)arguments: nullcaller: nulllength: 1name: "abort"prototype: {constructor: ƒ}__proto__: ƒ ()[[FunctionLocation]]: load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:4[[Scopes]]: Scopes[4]always: ƒ ()arguments: nullcaller: nulllength: 0name: "always"prototype: {constructor: ƒ}__proto__: ƒ ()[[FunctionLocation]]: load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:2[[Scopes]]: Scopes[4]complete: ƒ ()arguments: nullcaller: nulllength: 0name: "add"prototype: {constructor: ƒ}__proto__: ƒ ()[[FunctionLocation]]: load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:2[[Scopes]]: Scopes[4]done: ƒ ()error: ƒ ()fail: ƒ ()getAllResponseHeaders: ƒ ()getResponseHeader: ƒ (a)overrideMimeType: ƒ (a)pipe: ƒ ()progress: ƒ ()promise: ƒ (a)readyState: 4responseJSON: 0responseText: "0"setRequestHeader: ƒ (a,b)state: ƒ ()status: 400statusCode: ƒ (a)statusText: "Bad Request"success: ƒ ()then: ƒ ()__proto__: Object "=====error====="
有什么想法为什么不将k / v对发送到后端?我看到wordpress中的其他api发送了自己成功的ajax请求,但是我的不断失败。
答案 0 :(得分:0)
因为您使用的是(?=\b\d+)
,所以jQuery.ajax()
字段值格式由您自己决定。由于data
被定义为Content-Type
,因此application/x-www-form-urlencoded; charset=UTF-8
字段的值应类似于data
(表单数据格式的键值对)。 foo=Hello&bar=World
无法正常工作。
正确的代码如下:
{action: "selectTargetsWithOffset"}
jQuery.ajax({
type: "POST",
url: ajaxScript.ajaxUrl,
contentType : 'application/x-www-form-urlencoded; charset=UTF-8',
dataType: "json",
data: $.param({
action: "selectTargetsWithOffset"
}),
success: function(response) {
console.log(response, `=====success response=====`);
},
error: function(error) {
console.log(error, `=====error=====`);
}
});
会将JavaScript对象转换为数据格式的字符串。