简体   繁体   English

如何在 Chrome 扩展程序中使用 javascript 发出 POST 请求?

[英]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.我不希望它在表单提交时运行,但是当我调用 function 时我不希望它运行。

Would I use jQuery or AJAX?我会使用 jQuery 还是 AJAX?

You may use Fetch API on chrome to do so:您可以在 chrome 上使用Fetch API来执行此操作:


// 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 调用 php function 并存储其响应。

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

Make sure u include jquery CDN确保你包括 jquery CDN

You could use AJAX to post data to your PHP script, which will then run.您可以使用 AJAX 将数据发布到您的 PHP 脚本,然后该脚本将运行。

Note that jQuery and AJAX are not alternatives for each other.请注意,jQuery 和 AJAX 不能相互替代。

AJAX is an asynchronous HTTP request (which is what you want). AJAX 是异步 HTTP 请求(这是您想要的)。

jQuery is a javascript library which you can use to make AJAX calls. jQuery 是一个 javascript 库,您可以使用它来进行 AJAX 调用。

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

This is a shorthand function for making an ajax POST request.这是用于发出 ajax POST 请求的简写 function。 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.我也喜欢 Koala Yeung 的 Fetch 回答。 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.请记住,如果您想支持古老的浏览器(例如 Internet Explorer),您需要实现功能检测和回退,以防浏览器不支持获取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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