不知道如何使用AJAX [英] Not sure how to use AJAX

查看:118
本文介绍了不知道如何使用AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的这一点。我读过的书来学习JavaScript和HTML,所以很遗憾我还没有学到多少本。

我从来没有使用AJAX过,所以不知道它是如何工作的,在网上搜索,但发现所有的例子太复杂了。

基本上我想要做的是保存播放列表(虽然不能与饼干)。每个人都可以看到和附加到它(类似于一个评论部分)。 这只是一个例子,我在做别的事情,但是HTML + JS会有点大。只是想知道我怎么会做这样的事,这样我可以理解(希望)和其他地方应用它。

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

 <身体GT;
    <形式GT;
        <输入类型=文本ID =songInput大小=40占位符=歌曲名>
        &所述; IMG的id =Add按钮SRC =button.png>
    < /形式GT;
    < UL ID =播放列表>< / UL>
< /身体GT;

<脚本>
    在window.onload =负荷;
    功能负载(){
        VAR键=的document.getElementById(Add按钮);
        button.onclick = buttonClick;
    }
    传播buttonClick(){
        VAR文本=的document.getElementById(songInput);
        VAR歌= text.value;
        VAR键=的document.getElementById(Add按钮);
        VAR附加= document.createElement方法(礼);
        add.innerHTML =歌曲;
        变种UL =的document.getElementById(播放列表);
        ul.appendChild(补充);
    }
< / SCRIPT>
 

解决方案

首先,你必须明白什么是AJAX是。 AJAX是不是一种工具,您可以使用,相反,这是对技术的名称(异步JavaScript + XML)。基本上,它的意思是越来越/从/服务器发送的数据。

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

  VAR XHR =新XMLHtt prequest(); //创建一个XMLHtt prequest对象
xhr.open('得到',网址); //设置的类型和网址
xhr.onreadystatechange =功能(){//告诉它如何处理数据时的状态
                                         //改变
    如果(xhr.readyState === 4){// 4是$ C $下完成
         如果(xhr.status === 200){// code 200的意思是OK
            //成功
            VAR数据= xhr.responseText; //你的数据
        }其他{
            // //错误与错误的位置应对
        }
    }
};
xhr.send(空); //设置完成一切之后,发送
                                         // 请求。空在这里是指我们不发送 - 
                                         //荷兰国际集团任何服务器
 

它看起来复杂, XHR 被重复了很多。且不说我们要处理在IE 执行时。

目前该解决方案。我们将使用库来简化这个过程,让它做艰苦的工作,为我们的。

在jQuery的,这是你必须做一个基本的 XMLHtt prequest

  $。阿贾克斯({
    网址:网址,
    数据:{/ *数据在这里* /},
    类型:/ *GET或POST* /
})。完成(功能(数据){
    //成功
}),失败(函数(){
    //错误
});
//不复杂与jQuery
 

由于AJAX是一组技术来发送/接收数据,还有更多的是方法可以做到同一的事情。你可能认识的code以上仅适用于具有相同的域(您的服务器上的网页)的网址。要绕过这一限制,有一个名为 JSONP 的另一种技术。听起来很花哨,但它的意思是简单的使用<脚本> 标签来获取传递限制。当然,jQuery的一应俱全:

  $。阿贾克斯({
    网址:网址,
    数据:{/ *数据在这里* /},
    类型:/ *GET或POST* /,
    数据类型:JSONP//指定数据类型为JSONP
})。完成(功能(数据){
    //成功
});
 

下面是使用JSONP让内容从维基百科的一个简单的例子: http://jsfiddle.net/DerekL/ dp8vtjvt /
与正常的 XMLHtt prequest 调用维基百科的服务器是行不通的。然而,通过利用该 剧本标签不被同源策略就可以达到同样的事情的限​​制。请注意,对于JSONP工作,服务器必须在内部编程,允许返回一个JSON与包裹回拨电话。

I'm very new at this. I've read books to learn javascript and HTML, so unfortunately I haven't learn much about this.

I never used AJAX before, so not sure how it works, searched online, but find all examples too complicated.

Basically what I want to do is save a playlist (although not with cookies). Something everyone can see and add-on to it (similarly to a comments section). This is just an example, I'm doing something else, but the html + js would be a bit big. Just want to know how I would do it on this, so that I could understand it (hopefully) and apply it elsewhere.

This would be the body and below it the code I have (currently all my code is in [head]):

<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>

解决方案

First you have to understand what AJAX is. AJAX is not a "tool" that you can use, instead, it's a name for the techniques (asynchronous JavaScript + XML). Basically it means "getting/posting data from/to server."

In vallina JavaScript, XMLHttpRequest lets you send and receive data to and from a server:

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

It might look complicated, and xhr is repeated quite a lot. Not to mention the problems that we have to deal with when executing in IE.

There is solution for that. We will use libraries to simplify the process and let it do the hard works for us.

In jQuery, this is what you have to do to for a basic XMLHttpRequest:

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

Since AJAX is a group of techniques to send/receive data, there're more ways to do the "same" thing. You might realize the code above only works for URL that has the same domain (pages on your server). To bypass that limitation, there's another technique called JSONP. Sounds fancy, but what it means is simply "using the <script> tag to get pass that limitation". And of course, jQuery got you covered:

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

Here is a simple example of getting content off Wikipedia using JSONP: http://jsfiddle.net/DerekL/dp8vtjvt/
With a normal XMLHttpRequest call to Wikipedia's server would not work. However by exploiting the fact that script tags are not restricted by the Same-Origin Policy we can achieve the same thing. Note that for JSONP to work, the server must be programmed internally to allow returning a JSON with wrapped callback call.

这篇关于不知道如何使用AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆