我们正在使用js ajax调用来提取内容并将它们放在我们页面上的不同div中。
我们一直在为每个调用创建一个新函数,但是我们只想为它们使用一个函数。在尝试这个时 - 它只更新请求的最后一个div位置。
以下是请求:
<script type="text/javascript">
sendRequestFS('http://ourdomain.com/somepage.html', 'csad');
sendRequestFS('http://ourdomain.com/somepage1.html', 'fsad');
sendRequestFS('http://ourdomain.com/somepage2.html', 'tilead');
</script>
页面上的div:
<div id = 'csad'>CS Here</div>
<div id = 'fsad'>FS Here</div>
<div id = 'tilead'>Tiles Here</div>
我们正在使用的功能......每次都有某种方法可以使用同样的功能吗?
function createRequestObjectFS()
{
var returnObj = false;
if(window.XMLHttpRequest) {
returnObj = new XMLHttpRequest();
} else if(window.ActiveXObject) {
try {
returnObj = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
returnObj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return returnObj;
}
var httpFS = createRequestObjectFS();
var targetFS;
// This is the function to call, give it the script file you want to run and
// the div you want it to output to.
function sendRequestFS(scriptFileFS, targetElementFS)
{
targetFS = targetElementFS;
try{
// alert ("RQFS File: " + scriptFileFS + " Target : " + targetElementFS);
httpFS.open('get', scriptFileFS, true);
}
catch (e){
document.getElementById(targetFS).innerHTML = e;
return;
}
httpFS.onreadystatechange = handleResponseFS;
httpFS.send();
}
function handleResponseFS()
{
if(httpFS.readyState == 4) {
try{
// alert ("HRQFS");
var strResponseFS = httpFS.responseText;
document.getElementById(targetFS).innerHTML = strResponseFS;
} catch (e){
document.getElementById(targetFS).innerHTML = e;
}
}
}
答案 0 :(得分:0)
我重新安排了您的功能以使其正常工作:http://jsfiddle.net/q2Za2/1/
function createRequestObjectFS()
{
var returnObj = false;
if(window.XMLHttpRequest) {
returnObj = new XMLHttpRequest();
} else if(window.ActiveXObject) {
try {
returnObj = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
returnObj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return returnObj;
}
// This is the function to call, give it the script file you want to run and
// the div you want it to output to.
function sendRequestFS(scriptFileFS, targetElementFS)
{
var httpFS = createRequestObjectFS();
var targetFS;
function handleResponseFS()
{
if(httpFS.readyState == 4) {
try {
//alert ("HRQFS");
var strResponseFS = httpFS.responseText;
document.getElementById(targetFS).innerHTML = strResponseFS;
} catch (e){
document.getElementById(targetFS).innerHTML = e;
}
}
}
targetFS = targetElementFS;
try{
// alert ("RQFS File: " + scriptFileFS + " Target : " + targetElementFS);
httpFS.open('get', scriptFileFS, true);
}
catch (e){
document.getElementById(targetFS).innerHTML = e;
return;
}
httpFS.onreadystatechange = handleResponseFS;
httpFS.send();
}
sendRequestFS('https://r3dux.com/test_files/1.php', 'csad');
sendRequestFS('https://r3dux.com/test_files/2.php', 'fsad');
sendRequestFS('https://r3dux.com/test_files/3.php', 'tilead');