Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用AJAX运行具有src属性的脚本?_Javascript_Jquery - Fatal编程技术网

Javascript 如何使用AJAX运行具有src属性的脚本?

Javascript 如何使用AJAX运行具有src属性的脚本?,javascript,jquery,Javascript,Jquery,我在“page1.php”页面上有一个表单,如下所示: <form id = "form1" action = "page2.php"> </form> 执行Ajax函数后,我使用.append()将以下脚本添加到此表单中: 但是这个脚本没有运行,在用Ajax添加它之后,我如何运行它 注意:除了使用AJAX之外,我无法添加此脚本,因为“数据首选项id”属性将根据用户在屏幕上选择的内容而变化。您可以创建一个脚本标记,然后侦听onload事件以执行逻辑 const

我在“page1.php”页面上有一个表单,如下所示:

<form id = "form1" action = "page2.php">
</form>

执行Ajax函数后,我使用.append()将以下脚本添加到此表单中:


但是这个脚本没有运行,在用Ajax添加它之后,我如何运行它


注意:除了使用AJAX之外,我无法添加此脚本,因为“数据首选项id”属性将根据用户在屏幕上选择的内容而变化。

您可以创建一个
脚本标记,然后侦听onload事件以执行逻辑

const script = this.document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = url; // the script url like 
script.onload = () => {
  // your logic after script load
};

this.document.body.appendChild(script);

这适用于本地主机

var f = document.createElement("form");
f.setAttribute('method', "post");
f.setAttribute('action', "the-url-to-post");
$('#div_mercadopago').append(f);

var s = document.createElement("script");
s.setAttribute('src', 'https://www.mercadopago.com.br/integrations/v1/web-payment-checkout.js');
s.setAttribute('data-preference-id', Preference-ID**);

// add all elements to the form
document.body.appendChild(s);

**我假定您从webservice/ajax获得的首选项ID

为什么您确定新脚本不会执行?因为在执行此脚本时,屏幕上包含一个按钮。您可以尝试加载另一个脚本文件,以帮助您检测脚本是否可以执行。例如:创建一个名为
test.js
的文件,该文件包含类似于
alert('Hello!')的内容
,然后以当前方式将
test.js脚本附加到您的网站。
var f = document.createElement("form");
f.setAttribute('method', "post");
f.setAttribute('action', "the-url-to-post");
$('#div_mercadopago').append(f);

var s = document.createElement("script");
s.setAttribute('src', 'https://www.mercadopago.com.br/integrations/v1/web-payment-checkout.js');
s.setAttribute('data-preference-id', Preference-ID**);

// add all elements to the form
document.body.appendChild(s);