2012-08-07 72 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