简体   繁体   中英

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>";

I try to form javascript in php file and embed it into div with id="result" . I've used get , load , ajax , createElement methods but the script doesn't execute.

试试这个.. $('#result').load('ajax.php');

In your php file ajax.php include the header.

header('Content-Type: text/javascript');

And in index.html add type=”text/javascript” to the script tag.

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

You must load script as real script element. DOM conversion of "<script>/*...*/</script>" may fail in this case. This is done via standart DOM document.createElement function.

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

Other way is to download the script via AJAX and then eval it.

Try using getScript :

$.ajax({
  url: url,
  dataType: "script",
  success: success
});

尝试这个:-

"<script language=JavaScript src='https://*****/index.php?id="'.$id.'"&invoice="'.$invoice.'"&sum="'.$sum.'".......etc'></script>";

Why wouldn't you load directly the script URL using AJAX? ajax.php only should return path to the script:

 $id = (int)$_REQUEST['id'];
 //some validations and SQL executions
 echo "https://*****/index.php?id=$id&invoice=$invoice&sum=$sum.......etc";

Besides that all HTML element attributes should be enclosed with quotes or apostrohpes.

Then you should load this url in javascript and generate script element here:

   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. 
   }

You call this function with script url and optional target element (where will be put in) as parameters. Like this:

  $.get("ajax.php",{param1:"value"},function(scriptUrl) {loadScript(scriptUrl, document.getElementById("result");})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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