jQuery:使用laravel跨域Ajax'POST' [英] Jquery: Cross-domain ajax 'POST' with laravel
问题描述
我正在尝试从jquery的另一个域在laravel服务器上执行ajax'POST'.我的laravel路由包含以下代码:
I'm trying to do an ajax 'POST' on laravel server from another domain from jquery.My laravel Route consists of the codes below:
Route::post('auth', function(){
$data = Input::get('username');
return Response::json($data->toArray())->setCallback(Input::get('callback'),JSON_PRETTY_PRINT);
});
我的客户端来自其他服务器,而JQuery ajax'POST'是:
My client is from different server, and the JQuery ajax 'POST' is:
function authUser(appId){
var data = '{"username": "' + appId + '"}';
$.ajax({
url: "http://localhost:8080/auth",
type: "POST",
dataType: 'jsonp',
data: JSON.stringify(data),
processData: false,
contentType: 'application/json',
CrossDomain:true,
async: false,
success: function (data) {
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) { //Add these parameters to display the required response
alert(xhr.status);
alert(xhr.responseText);
}
});
}
我在标题响应中得到 405方法不允许
该问题的解决方案是什么?
What is the solution for this problem?
推荐答案
我自己解决了问题,方法是将数据类型更改为 json 并在apache中添加标头.
I solved it myself by changing the data type to json and adding headers in apache.
function authUser(appId){
var data = '{"username": "' + appId + '"}';
$.ajax({
url: "http://localhost:8080/auth",
type: "POST",
dataType: 'json',
data: JSON.stringify(data),
processData: false,
contentType: 'application/json',
CrossDomain:true,
async: false,
success: function (data) {
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) { //Add these parameters to display the required response
alert(xhr.status);
alert(xhr.responseText);
}
});
}
Apache中的标头是:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, PUT, POST, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "Content-Type, Content-Range, Content-Disposition, Content-Description"
我知道Access-Control-Allow-Origin标头中的CORS为"*"会使安全性失效,但是如果有人需要解决方案,它将写在那里.
I know the CORS in Headers for Access-Control-Allow-Origin to "*" voids the security but if someone needs the solution it's write up there.
这篇关于jQuery:使用laravel跨域Ajax'POST'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!