JavaScript相当于jQuery的$ .ajax函数

时间:2014-03-30 08:50:43

标签: javascript jquery ajax

我有以下jQuery代码:

dataString = 'test'; // array?
$.ajax({
    type: "POST",
    url: "tokenize.php",
    data: {
        data: dataString
    }, 
    cache: false,
    success: function (data) {
        returnedvalue = data;
        console.log(data); //alert isn't for debugging
    }
});

这个jQuery代码工作正常,但我想要一个简单的JavaScript代码,我无法弄清楚该怎么做。我只在Stack Overflow的帮助下编写了这段代码。

我已经看到可以使用XMLHttpRequest完成此操作:

var http = new XMLHttpRequest();
var url = "tokenize.php";
var params = "lorem=ipsum&name=binny"; // What will be done here in my case?
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

// Call a function when the state changes.
http.onreadystatechange = function () {
    if (http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);

1 个答案:

答案 0 :(得分:0)

application/x-www-form-urlencoded数据的格式为:

key=value&key=value&key=value

通过encodeURIComponent运行每个键和值,以处理具有特殊含义或编码中不允许的字符。