2012-08-07 32 views
0

爲了讓我的代碼幾乎完全寫在Jquery中,我想重寫一個AJAX調用jquery。Javascript的AJAX調用jquery調用

這是一個從網頁到Tomcat servlet的調用。

的我現在的情況類似代碼:

var http = new XMLhttpRequest(); 
var url = "http://example.com/MessageController?action=send"; 

http.onreadystatechange = function() 
if (http.readyState == 4) 
{ 
    if (http.status == 200){ var response = http.responseText;} 
    else {/*code2*/} 
}; 
http.async = false; 
http.open("POST", url, true); 
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
http.send(string); 

這將是做到這一點的最好方法是什麼? .ajax.post?你能幫我用一些僞代碼來啓動它嗎?

+0

你想你的電話是異步的?你當前的調用會被阻塞,因爲你設置了http.async = false,而jquery.ajax默認是異步的。 – 2012-08-07 15:37:10

+0

不確定。這工作正常。異步,將不會重新加載整個網頁? – jacktrades 2012-08-07 15:40:44

+1

異步意味着你的AJAX調用不會阻塞更多的javascript代碼,通常更重要的是,瀏覽器的UI線程。換句話說,瀏覽器在等待從服務器獲取數據時不會「掛起」。 http://blogs.msdn.com/b/wer/archive/2011/08/03/why-you-should-use-xmlhttprequest-asynchronously.aspx – 2012-08-07 15:55:42

回答

1

使用.ajax或(如您正在使用POST).post

$.ajax({ 
    url: "http://example.com/MessageController", 
    type: "POST", 
    data: { action: "send", yourStringName: "something" }, 
    async: false, // make sure you really need it 
    contentType:'application/x-www-form-urlencoded' 
}).done(function(response) { 
    console.log(response); 
}); 

不要緊,你用哪一個,因爲.post是簡寫.ajax

+0

謝謝,你能重寫上面的僞代碼嗎? – jacktrades 2012-08-07 15:35:26

+0

檢查我編輯的答案。 – Zbigniew 2012-08-07 15:36:34

+0

你能重寫一下我的情況更具體嗎?像我在哪裏編寫內容類型,我想要傳遞的字符串在哪裏進行... – jacktrades 2012-08-07 15:38:18

1

您可以使用jQuery post

var url="MessageController" 
$.post(url, { action : "send"} ,function(data){ 
    //response from MessageController is in data variable 
    //code 1 
    alert(data) 
}).error(function(){ 
     alert("error"); //code 2 
    }) 

假設MessageController是在你的域某些URL,你知道的same origin policy

+0

code1和code2去哪裏? – jacktrades 2012-08-07 15:42:18

+0

@jacktrades:看我的更新 – Shyju 2012-08-07 15:45:18

+0

謝謝。不明白 - >在jquery文檔中,數據是要發送到服務器的數據,但是,您編寫的響應是在數據變量中。請寫下'串'在哪裏。另外我如何在這裏設置異步'假'? – jacktrades 2012-08-07 15:49:08