简体   繁体   中英

How to make POST request with javascript in a Chrome Extension?

I was wondering if there is anyway to make this:

<form action="http[://localhost/.../script.php" method="POST">

a regular call. I don't want it to run on form submit, but instead I wan't it to run when I call a function.

Would I use jQuery or AJAX?

You may use Fetch API on chrome to do so:


// building your form values
var data = new URLSearchParams();
data.set('var1', 'value 1');
data.set('var2', 'value 2');

// send to the endpoint
fetch("http://localhost/.../script.php", {
        method: 'POST',
        mode: 'no-cors',
        cache: 'no-cache',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: data
    }).then(function(response) {
        // check the response object for result
        // ...
    });

You can use ajax to call the the php function and store its response.

$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
  }});

Make sure u include jquery CDN

You could use AJAX to post data to your PHP script, which will then run.

Note that jQuery and AJAX are not alternatives for each other.

AJAX is an asynchronous HTTP request (which is what you want).

jQuery is a javascript library which you can use to make AJAX calls.

I would take a look at https://api.jquery.com/jQuery.post/

This is a shorthand function for making an ajax POST request. Eg:

function triggerMyPhpScript(data) {
    $.post("http://localhost/.../script.php", data, function(responseData) {
        // do something with the response of your script
    });
}

I also like the Fetch answer from Koala Yeung. This will also work fine on modern browsers. Keep in mind that if you want to support ancient browsers (eg internet explorer), you need to implement feature detection and a fallback in case fetch is not supported by the browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM