不知道如何使用AJAX

问题描述:

我很新。我读过书籍来学习JavaScript和HTML,所以很遗憾我没有学到太多的东西。不知道如何使用AJAX

我以前从未使用AJAX,所以不知道它是如何工作的,在线搜索,但找到所有例子太复杂。

基本上我想要做的是保存播放列表(虽然不是用cookie)。每个人都可以看到并添加到它(类似于评论部分)。 这只是一个例子,我正在做其他事情,但html + js会有点大。只是想知道我会如何做到这一点,以便我能够理解它(希望)并将它应用到其他地方。

这将是身体和它下面的代码,我有(目前我所有的代码是在[主治]):

<body> 
    <form> 
     <input type="text" id="songInput" size="40" placeholder="Song Name"> 
     <img id="addButton" src="button.png"> 
    </form> 
    <ul id="playlist"></ul> 
</body> 

<script> 
    window.onload = load; 
    function load() { 
     var button = document.getElementById("addButton"); 
     button.onclick = buttonClick; 
    } 
    function buttonClick() { 
     var text = document.getElementById("songInput"); 
     var song = text.value; 
     var button = document.getElementById("addButton"); 
     var add = document.createElement("li"); 
     add.innerHTML = song; 
     var ul = document.getElementById("playlist"); 
     ul.appendChild(add); 
    } 
</script> 
+3

那么,你尝试谷歌吗?有很多使用AJAX的例子 - [lmgtfy](http://bit.ly/17JgvGE) – Vucko 2014-08-29 06:02:57

+0

所以你有一个背面的某种数据库?我建议你看看这个:https://togetherjs.com/。这就像它变得简单一样。另一个技巧是使用jQuery进行Ajax和dom操作,因为它非常简单易学,而且互联网充满了jQuery的技巧和窍门。 – 2014-08-29 06:15:16

+0

通过这个网页,有很多的例子。请谷歌。 – Leo 2014-08-29 06:17:10

首先,你必须了解AJAX是什么。 AJAX不是您可以使用的“工具”,相反,它是该技术的名称(异步JavaScript + XML)。基本上这意味着“从/到服务器获取/发布数据”。

在Vallina酒店的JavaScript,XMLHttpRequest让您发送和接收数据,并从服务器:

var xhr = new XMLHttpRequest();   //Create an XMLHttpRequest object 
xhr.open('get', url);     //Set the type and URL 
xhr.onreadystatechange = function(){  //Tell it what to do with the data when state 
             // changes 
    if(xhr.readyState === 4){   //4 is the code for "finished" 
     if(xhr.status === 200){   //Code 200 means "OK" 
      //success 
      var data = xhr.responseText; //Your data 
     }else{ 
      //error      //Deal with errors here 
     } 
    } 
}; 
xhr.send(null);       //After finished setting everything, send the 
             // request. null here means we are not send- 
             // ing anything to the server 

它看起来复杂,xhr被重复了很多。更何况we have to deal with when executing in IE的问题。

有解决方案。我们将使用图书馆来简化流程,并让它为我们完成艰苦的工作。

In jQuery,这是你必须做的一个基本XMLHttpRequest什么:

$.ajax({ 
    url: url, 
    data: { /*data here*/ }, 
    type: /*"GET" or "POST"*/ 
}).done(function(data){ 
    //success 
}).fail(function(){ 
    //error 
}); 
//Not complicated at all with jQuery 

由于AJAX是一组技术来发送/接收数据,还有更多的是如何做“相同”事情。您可能会意识到上面的代码仅适用于具有相同域的URL(服务器上的页面)。为了绕过这个限制,还有另一种叫做JSONP的技术。听起来很花哨,但它意味着什么只是“使用<script>标签来通过该限制”。当然,jQuery的一应俱全:

$.ajax({ 
    url: url, 
    data: { /*data here*/ }, 
    type: /*"GET" or "POST"*/, 
    dataType: "JSONP"    //specifying dataType to be JSONP 
}).done(function(data){ 
    //success 
}); 

这里是获得使用JSONP关闭*的内容的一个简单的例子:http://jsfiddle.net/DerekL/dp8vtjvt/
与正常XMLHttpRequest调用Wikipedia's server是行不通的。然而,通过利用script tags are not restricted by the Same-Origin Policy这个事实,我们可以实现同样的事情。请注意,要使JSONP正常工作,必须在内部对服务器进行编程,以允许通过包装回调呼叫返回JSON。