我正在尝试验证一个API,它只允许您使用以JSON作为表单数据的POST进行验证,格式为{"username":"myusername","password":"mypassword"}。
我已经尝试了两天来让它在jQuery上工作,但我遇到了问题,因为它是跨域的。我如何才能做到这一点呢?
错误消息:
Request Method:OPTIONS
Status Code:405 METHOD NOT ALLOWED
到目前为止的代码:
var username = "myusername";
var password = "mypass"
var authurl = "https://myurl";
$.ajax
({
type: "POST",
url: authurl,
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: false,
data: {'json':'{"username":"' + username + '", "password":"' + password + '"}'},
success: function (result) {
$('#json').html(result);
}
})
总结一下:
用户名API只接受身份验证的POST 用户名API需要json作为表单数据,例如:{“
非常感谢您的帮助:)
发布于 2011-07-20 20:40:11
您应该遵循不同的模式。您的本地JS将对本地URL执行ajax post,该URL将接受包含json数据的POST方法。
此时,您的服务器代码将使用适当的数据向远程服务器执行HTTP POST,获取响应,并将其发送回调用js。
发布于 2011-07-20 20:41:52
问题是,您尝试发布的域名不会响应在每次跨域请求之前发送的OPTIONS请求。通过OPTIONS请求,浏览器接收关于跨域规则等的信息。要启用跨域请求,服务器必须设置Access-Control-Allow-Origin:*
(或脚本的域,实际上,但*涵盖所有内容)以及可能的Access-Control-Allow-Methods: GET, POST, OPTIONS
标头。
发布于 2013-05-03 00:08:56
我在GoDaddy上有一个共享主机。我也需要这个问题的答案,在四处搜索后,我发现这是可能的。
我编写了一个.htaccess文件,将其放在与我的操作页面相同的文件夹中。以下是.htaccess文件的内容:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
下面是我的ajax调用:
$.ajax({
url: 'http://www.mydomain.com/myactionpagefolder/gbactionpage.php', //server script to process data
type: 'POST',
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: beforeSendHandler,
success: completeHandler,
error: errorHandler,
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});
参考这篇文章:
Header set Access-Control-Allow-Origin in .htaccess doesn't work
https://stackoverflow.com/questions/6761982
复制相似问题