如何在告诉网站做某事时使用XMLHttpRequest?

时间:2018-02-13 00:06:40

标签: javascript ajax

首先,我必须说我在Ajax中有 NO EXPERIENCE ,我只需要这个解释就可以创建一个简单的chrome扩展。 在互联网上找不到太多东西,即使我认为这很简单。 我需要一部分代码,我会打电话给#34;来自网站的网址,我需要调整该网址中的某些参数。

请求网址http://URL_OF_THE_WEBSITE/v1/send?token=TOKEN_VALUE

请求方法:POST

请求有效负载

{amount:1,user_id:12345678}

数量:1 user_id:12345678

(这是我从网络面板获得的东西 - 网址和令牌更改为真实的东西 - 同时从网站自动调用网址,但我也需要能够手动调用它。)< / p>

所以我想要混合使用AJAX(我不知道)和JS,以便我调用这个url。 我会为TOKEN_VALUE和amount&amp; user_id使用变量,但我不知道如何调用该url以及如何设置&#34;请求有效负载&#34;为了让网站做我想做的事情。

如果有人愿意帮助我,我真的很感激:)。

我已经完成的工作,但没有工作:

var request=new XMLHttpRequest;
request.open("POST","https://URL_OF_THE_WEBSITE/v1/send?token=TOKEN_VALUE"),request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"),request.Payload("user_id=12345678&amount=5");

我基本上试图重新制作一个我在网上找到的例子,但它没有成功,因此我需要有人向我解释这是如何工作的,以及如何调整我需要的参数。

1 个答案:

答案 0 :(得分:0)

function callAjax() {
    // the XMLHttpRequest returns the ajax object that has several cool methods, so you store it in the request variable
    // @data contains the $_POST[amount],$_POST[user_id],$_POST[whatever] since we are using POST method, if you're using PHP as a server side language
    var request = new XMLHttpRequest(),
        url = 'place_here_the_url_only',
        data = 'amount=1&user_id=12345678&whatever=dataYouWantToSendToServerFromBrowser',
        token = document.querySelector('meta[name="csrf-token"]').content;

    // when the server is done and it came back with the data you can handle it here
    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            // do whatever you want!
            console.log("The request and response was successful!");
       }
    };

    // method post, your giving it the URL, true means asynchronous
    request.open('POST', url, true);
    // set the headers so that the server knows who is he talking to, I'm using laravel 5.5
    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
    // Token needed
    request.setRequestHeader('X-CSRF-TOKEN', token);
    // then you send the data and wait for the server to return the response
    request.send(data);
}

Ajax:异步JavaScript和XML

这是浏览器和托管网站的服务器之间的通信方式,它不能调用任何其他服务器。

异步表示网站继续正常运行,直到从服务器返回请求并且:

if (this.readyState == 4 && this.status == 200) { }

被触发