我想從一個常見的html文件(要加載到手機上)發送一個ajax請求到我的服務器,並在這裏有一些問題。使用Ajax從手機從RAILS 3服務器調用JSON服務器
如果我使用RestClient,從WizTools我可以很容易地創建一個與正文{"email":"myemail", "password":"mypassword"}
json POST命令,並設置標頭"Content-type":"application/json"
和"Accept":"application/json"
。
但是從瀏覽器中,當我添加contentType時,它只是發送OPTIONS方法而不是POST,並且服務器期待POST。如果我將contentType標記取出,請求會與POST保持一致,但服務器無法將其識別爲JSON,因此會阻止該請求。
爲什麼會發生這種情況?我該如何解決這個問題並列出用戶的數據?
<html>
<head>
<script src="jquery-1.7.2.min.js"></script>
<script src="jquery.mobile-1.2.0-alpha.1.min.js"></script>
<script>
function runAjax() {
var url_p = "https://myserver/list";
var emailVal = "[email protected]"
var passwordVal = "mypwd"
$.ajax({
type: 'POST',
url: url_p,
dataType: "application/json",
contentType: "application/json; charset=utf-8",
data: { "email": emailVal, "password": passwordVal },
success: function (data, textStatus, jqXHR) {
$("#result").html(data);
},
error: function(jqXHR,error, errorThrown) {
if(jqXHR.status&&jqXHR.status==400){
alert(jqXHR.responseText);
}else{
alert("Something went wrong");
}
},
dataType: "json"
});
}
function resetValue(){
$("#result").html("");
}
</script>
</head>
<body>
<button onclick="runAjax()">Post Ajax call</button>
<button onclick="resetValue()">Reset value</button>
<p>Result</p>
<p id="result"></p>
</body>
</html>
感謝
編輯
這似乎是跨域問題與阿賈克斯。我曾嘗試使用jsonp作爲數據類型,但隨後HTTP與GET請求,而不是POST ...
我在2010年看到,它是不可能使用跨域jsonp POST。如果現在是..我..難怪
EDIT 2
我結束了使用該Ajax代碼(學分佩德羅卡莫納):
<html>
<head>
<script src="jquery-1.7.2.min.js"></script>
<script src="jquery.mobile-1.2.0-alpha.1.min.js"></script>
<script>
function rpc_call(){
var http = new XMLHttpRequest();
var url = "https://yourserver/list";
var params = "email=Useremail&password=pwd";
http.open("POST", url, true);
http.setRequestHeader("Accept", "application/json");
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
$("#resposta").html(http.responseText);
}
}
http.send(params);
}
function apagaConteudo(){
$("#resposta").html("");
}
</script>
</head>
<body>
<button onclick="rpc_call()">Post Ajax call</button>
<button onclick="apagaConteudo()">Apagar conteudo</button>
<p>Resposta</p>
<p id="resposta">____Cena______</p>
</body>
</html>