繁体   English   中英

如何嵌入和执行JavaScript到HTML?

[英]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中。 我使用了getloadajaxcreateElement方法,但脚本没有执行。

试试这个.. $('#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.

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