开发者

Ajax alerts the response, but won't add it to the dom

开发者 https://www.devze.com 2023-02-11 05:22 出处:网络
I have this funct开发者_开发问答ion handling ajax calls: function ajaxPost (divNode, parameters, file) {

I have this funct开发者_开发问答ion handling ajax calls:

function ajaxPost (divNode, parameters, file) {

if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  } else {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    alert (xmlhttp.responseText);
    divNode.appendChild (xmlhttp.responseText);
    }
  }

xmlhttp.open("POST", file, true);

//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);
}

The alert about halfway down gives me the expected output from the given php file, but for some reason, I don't seem able to append it to the dom. I have checked the divNode is actually a div element & I'm successfully using appendChild else-where, so I'm at a loss to understand the problem here.

What is different about an Ajax call to disrupt normal javascript functions and how do I work around it?


The appendChild method takes an HTMLElementNode (or other DOM node object) as an argument, not a String

You need to build a DOM tree using createElement and createTextNode and then append that. This is a good solution combined with a server returning a neat data structure expressed in JSON.

Alternatively, you could look at innerHTML.


Change divNode.appendChild (xmlhttp.responseText);

to

jQuery:

$(divNode).appendChild (xmlhttp.responseText);

And change what you're passing in as divNode to something like '.classname' or '#idname'

Or Non jQuery:

document.getElementById(divNode).appen... divNode would need to be an ID of the element

0

精彩评论

暂无评论...
验证码 换一张
取 消