admin管理员组

文章数量:1415664

The below is just a bit of my ajax code, at the moment my variable 'resp' is returning an entire response from test.php. Is there any way I can just return the responseText between a specified tag? ie. just get back the responseText of the html inside test.php's div of id="xyz"?

var loc="test.php?myinput=apple";
ajax.onreadystatechange=function() {
        if (ajax.readyState==4  && ajax.status == 200) {    
            var resp =  ajax.responseText;
        }
    }
ajax.open("GET",loc,true);
ajax.send(null);

The below is just a bit of my ajax code, at the moment my variable 'resp' is returning an entire response from test.php. Is there any way I can just return the responseText between a specified tag? ie. just get back the responseText of the html inside test.php's div of id="xyz"?

var loc="test.php?myinput=apple";
ajax.onreadystatechange=function() {
        if (ajax.readyState==4  && ajax.status == 200) {    
            var resp =  ajax.responseText;
        }
    }
ajax.open("GET",loc,true);
ajax.send(null);
Share Improve this question asked May 10, 2011 at 12:50 tooptoop 512 bronze badges 2
  • You could use a library to parse the response HTML, and then find the DIV via a CSS selector. Like so: $(resp).find('#xyz') – Šime Vidas Commented May 10, 2011 at 12:57
  • If you are interested in the source text content of the DIV, I remend a server-side script that would return it instead of searching for it via JavaScript. – Šime Vidas Commented May 10, 2011 at 13:07
Add a ment  | 

4 Answers 4

Reset to default 2

You could use jquery shorthand function load() to do this in a swift

$('#result').load('test.php' #container');

here result is the div where you want to place the response text and container is the your specified source element location of test.php

is this what you want?

change your ajax code to:

if (ajax.readyState==4  && ajax.status == 200) {    
   eval(ajax.responseText);
}

then in the test.php page, write for response like this

echo "document.getElementById('xyz').innerHTML='abc';";

If you are willing to switch to jQuery you could do the following

$.ajax({
    url: 'test.php?myinput=apple',
    method: 'POST',
    success : function( data ) {
        var content = $(data).find('#xyz').text();
        // alternativly the HTML
        // var content = $(data).find('#xyz').html();
    }
});

Are you trying to update some portion of your HTML with that response? If so, you can use jQuery and call the load method that accepts a special URL parameter to load a portion of the returned HTML:

Working example: http://jsfiddle/marcosfromero/P5KTv/

本文标签: javascriptajaxreturn only part of responsetextStack Overflow