我试图使用Ajax将表单的内容发送到WordPress插件。我遵循了许多教程和例子。到目前为止,还没有人提出申请。
/wp-content/plugins/tr/trplugin.php:
function trplugin_SC_viewTR($atts) {
wp_enqueue_script( 'wp-util' );
wp_enqueue_script('jquery-ui-widget');
wp_enqueue_script('jquery-ui-autocomplete');
wp_enqueue_script('jquery-ui-button');
wp_enqueue_script('trplugin-core',
plugin_dir_url(__FILE__).'js/tr.js',
array('jquery-ui-widget','jquery-ui-autocomplete','jquery-ui-button',),
'0.0.1',
TRUE
);
$wpAjax = array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'trplugin-core' )
);
wp_localize_script('trplugin-core', 'wpAjax', $wpAjax );
}
add_shortcode('tr-view', 'trplugin_SC_viewTR');
function post_flagtr() {
echo json_encode(array('123','abc'));
wp_die();
}
add_action( 'wp_ajax_flag_tr', 'post_flagtr' );包含JS文件的摘录: tr.js
jQuery('#exampleDIV').append(
jQuery('<a id="trView_flagSUBMIT" class="makeButton">Submit Report</a>').on('click',function(event) {
formDATA = jQuery('form#trView_flagFORM').find('input:visible,textarea:visible').serializeArray();
postTHIS = [];
formDATA.forEach(function(i) {
postTHIS[i.name] = i.value;
});
postTHIS.action = 'flag_tr';
postTHIS.nonce = wpAjax.nonce;
console.log(postTHIS);
console.log(wpAjax);
tryTHIS = 1;
if ( tryTHIS === 1 ) {
jQuery.ajax({
type : 'POST',
dataType : 'json',
headers: {
'Content-Type':'application/x-www-form-urlencoded;'
},
url : wpAjax.ajax_url,
data : postTHIS,
success: function(response) {
console.log(response);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("errorThrown="+ errorThrown+", textStatus=" + textStatus, jqXHR);
}
});
} else if ( tryTHIS === 2 ) {
jQuery.post(wpAjax.ajax_url, postTHIS, function(response) {
console.log(response);
}
);
} else if ( tryTHIS === 3 ) {
wp.ajax.post('flag_tr', postTHIS).done(function(response) {
console.log(response);
}
);
} else if ( tryTHIS === 4 ) {
fetch(wpAjax.ajax_url, {
method: "POST",
body: postTHIS,
}).then((resp) => {
console.log(resp);
}).catch((resp) => {
console.log(resp);
});
}
})
);tryTHIS的任何值都会导致相同的结果,即不向服务器发送HTTP。
注意:trplugin-core是我的工作,而tr是经过编辑的命名空间,实际上我在代码中使用了一个更长的名称。
编辑:执行FeniX的建议,如#1所示,结果如下:
errorThrown=Bad请求、textStatus=error、jqXHR=[对象对象]
服务器日志中没有错误。
发布于 2021-03-07 21:32:15
试一试,第一种类型,但实现“错误:”分支,以查看您的错误。(可能会发生这样的情况,您可能必须在某一时刻对数据使用JSON.stringify()函数。)
error: function (jqXHR, textStatus, errorThrown)
{
console.log("errorThrown="+ errorThrown+", textStatus=" + textStatus + ", jqXHR=" + jqXHR);
}发布于 2021-03-09 01:01:04
问题是这条线:
postTHIS = [];它必须是:
postTHIS = {};发布于 2021-03-10 06:24:52
抓得好!尽管文档中有这样的声明:(Data) Type: PlainObject or String or Array。在某种程度上,数组被转换为字符串类型,并被不同地对待。( https://api.jquery.com/jquery.ajax/ )
https://stackoverflow.com/questions/66521109
复制相似问题