ajax怎么在html与php中使用,php – 如何在通过ajax加载的html中运行javascript

如果您想按需加载Javascript.这可以通过动态创建脚本标记来完成.这种模式在

Stoyan Stefanov书 –

Javascript Patterns中有所说明

这本书剪了一下:

写一个require函数.然后这样称呼它:

require("extra.js", function () {

functionDefinedInExtraJS();

});

样品需要功能:

function require(file, callback) {

var script = document.getElementsByTagName('script')[0],

newjs = document.createElement('script');

// IE

newjs.onreadystatechange = function () {

if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {

callback();

}

};

// others

newjs.onload = function () {

callback();

};

newjs.src = file;

script.parentNode.insertBefore(newjs, script);

}

@Edit:更多针对您案例的详细信息.我会尽量简单:

创建四个文件:

> index.php:测试文件.

> code.js:具有Ajax,getJS,getHTML函数的实际代码

> content.php:任何将在没有任何JS的情况下打印纯HTML的PHP​​文件

> content.js:您想要动态运行的JavaScript代码.

的index.php

content.php

Hello, I am dynamic span came from content.php

content.js

//Ana javascript code you want to run it by Ajax function should go inside this function

function executeJS(element){

element.innerHTML = "Hello, I am dynamic span came from content.js";

}

code.js

//This function responsible for doing the ajax request for any file that will return pure HTML.

function getHTML(url, element){

var i, xhr, activeXids = [

'MSXML2.XMLHTTP.3.0',

'MSXML2.XMLHTTP',

'Microsoft.XMLHTTP'

];

if (typeof XMLHttpRequest === "function") { // native XHR

xhr = new XMLHttpRequest();

} else { // IE before 7

for (i = 0; i < activeXids.length; i += 1) {

try {

xhr = new ActiveXObject(activeXids[i]);

break;

} catch (e) {}

}

}

xhr.onreadystatechange = function () {

if (xhr.readyState !== 4) {

return false;

}

if (xhr.status !== 200) {

alert("Error, status code: " + xhr.status);

return false;

}

element.innerHTML += xhr.responseText;

};

xhr.open("GET", url, true);

xhr.send("");

}

//This function will load javascript file on-demand and call executeJS function inside that file.

function getJS(url, element, cb){

var newjs = document.createElement('script');

// IE

newjs.onreadystatechange = function () {

if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {

cb();

}

};

// others

newjs.onload = function () {

cb();

};

newjs.src = url;

element.appendChild(newjs);

}

//This is same as your function, but now can handle both PHP and JS files

function Ajax(url, id){

var element = document.getElementById(id),

regex = /\.js$/;

if(!element){

alert("Invalid ID");

return false;

}

if(regex.test(url)){ //If url ends with JS, load using getJS

getJS(url, element, function(){

executeJS(element);

});

} else {

getHTML(url, element);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值