[英]How Embed a HTML form with additional element on condition using JavaScript
[英]How to embed & execute javascript into html?
的index.html
<script>
function check() {
var id = $('input[name=id]').val();
$("#result").load("/ajax.php", {id:id});
}
</script>
<input type="text" size="3" name="id"><br />
<button onclick="check();">Pay</button>
<div id="result"></div>
ajax.php
<?php
$id = (int)$_REQUEST['id'];
//some validations and SQL executions
echo "<script language=JavaScript src='https://*****/index.php?id=$id&invoice=$invoice&sum=$sum.......etc'></script>";
我嘗試在php文件中形成javascript並將其嵌入到id="result"
div中。 我使用了get
, load
, ajax
, createElement
方法,但腳本沒有執行。
試試這個.. $('#result').load('ajax.php');
在你的php文件中,ajax.php包含頭文件。
header('Content-Type: text/javascript');
並在index.html中將script =“text / javascript”添加到腳本標記中。
<script type=”text/javascript”>
function check() {
var id = $('input[name=id]').val();
$("#result").load("/ajax.php", {id:id});
}
</script>
您必須將腳本作為真實腳本元素加載。 在這種情況下, "<script>/*...*/</script>"
DOM轉換可能會失敗。 這是通過標准DOM document.createElement
函數完成的。
var script = document.createElement("script");
script.src = path;
其他方法是通過AJAX下載腳本然后評估它。
嘗試使用getScript :
$.ajax({
url: url,
dataType: "script",
success: success
});
嘗試這個:-
"<script language=JavaScript src='https://*****/index.php?id="'.$id.'"&invoice="'.$invoice.'"&sum="'.$sum.'".......etc'></script>";
為什么不使用AJAX直接加載腳本URL? ajax.php只應該返回腳本的路徑:
$id = (int)$_REQUEST['id'];
//some validations and SQL executions
echo "https://*****/index.php?id=$id&invoice=$invoice&sum=$sum.......etc";
除此之外,所有HTML元素屬性都應該用引號或者apostro括起來。
然后你應該在javascript中加載這個url並在這里生成腳本元素:
function loadScript(url,appendTo) {
var script = document.createElement("script")
script.type = "text/javascript";
script.src = url;
if(typeof appendTo.appendChild == "function") //Chceking if we can append script to given element
appendTo.appendChild(script);
else
document.body.appendChild(script) //This will not work in old IE, where document.body is not defined.
}
您可以使用腳本URL和可選的目標元素(將放入的位置)作為參數調用此函數。 像這樣:
$.get("ajax.php",{param1:"value"},function(scriptUrl) {loadScript(scriptUrl, document.getElementById("result");})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.