我必须在wordpress中通过AJAX将数据发布到另一个网站(http://123abc.com/register) .但我总是出错。这是我的jquery AJAX代码:
<script>
$(document).ready(function() {
// process the form
$(\'form\').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
\'fname\' : $(\'input[name=fname]\').val(),
\'lname\' : $(\'input[name=lname]\').val(),
\'email\' : $(\'input[name=email]\').val(),
\'password\' : $(\'input[name=password]\').val(),
\'gender\' : $(\'input[name=gender]\').val(),
\'accent\' : $(\'input[name=accent]\').val(),
\'type\' : $(\'input[name=type]\').val(),
};
// process the form
$.ajax({
type : \'POST\', // define the type of HTTP verb we want to use (POST for our form)
url : \'http://123abc.com/register\', // the url where we want to POST
data : formData, // our data object
dataType : \'json\',
encode : true,
success: function(data){
if(data.error){
//show error message here
$(\'#name-group\').append(\'<div class="help-block">\' + data.errors + \'</div>\');
}else{
//handle success part
$(\'#name-group\').append(\'<div class="help-block">\' + data.message + \'</div>\');
}
},
error: function(jqXHR, textStatus, errorThrown){
//request error
$(\'#name-group\').html(\'<p>status code: \'+jqXHR.status+\'</p><p>errorThrown: \' + errorThrown + \'</p><p>jqXHR.responseText:</p><div>\'+jqXHR.responseText + \'</div>\');
console.log(\'jqXHR:\');
console.log(jqXHR);
console.log(\'textStatus:\');
console.log(textStatus);
console.log(\'errorThrown:\');
console.log(errorThrown);
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
</script>
请帮忙。提前感谢
最合适的回答,由SO网友:webtoure 整理而成
由于“同源策略”,这将不起作用,除非您尝试访问的服务器专门允许这些类型的请求Access-Control-Allow-Origin: *
. 您可以在上阅读文档MDN 以获取有关此主题的更多信息。
根据我的测试,服务器还需要配置另一个标头,即Access-Control-Allow-Headers
因此,如果我们结合这两个选项,有效的设置可能如下所示:
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type, Accept, Authorization, X-Requested-With