如何嵌入&;将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中,将type="text/javascript"添加到脚本标记中。

<script type=”text/javascript”>
        function check() {
           var id = $('input[name=id]').val();
           $("#result").load("/ajax.php", {id:id});        
         }
   </script>

您必须将脚本加载为真正的脚本元素。在这种情况下,CCD_ 7的DOM转换可能失败。这是通过标准DOM document.createElement函数完成的。

var script = document.createElement("script");
script.src = path;

另一种方法是通过AJAX下载脚本,然后eval它。

尝试使用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元素属性都应该用引号或撇号括起来。

然后你应该在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");})