0

How to extract html element into a variable after data is successfully returned from an ajax response?

This is the ajax call containing the following returned data

   $.getJSON("test.php",function(data)
   {
        $.each(data, function(key, value)
        {
             alert(value); // this is working but don't know how to extract the strong element from the p element into a variable
        });
   });

I get the following html data returned from an ajax response

          <p id="testResults"><strong id="testNumber">Test 1</strong> passed - date </p>

How do I get the strong html element into a variable for later usage like this....

        var testNumberHtml = "<strong id='testNumber'>Test 1</strong>";

and then put the p element into another variable, like this...

       var testResultsHtml =  "<p id="testResults"> passed - date </p>";
4

1 回答 1

0

You might have to do a little trickery to separate those. I would suggest having server side send them separated like this:

{p: "<p id="testResults"> passed - date </p>", 
 strong: "<p id="testResults"> passed - date </p>"}

If that is not an option, you can probably do it like this in javascript:

html

<div id="contentResult" style="display:none;"></div>​

js

var jsonResult = '<p id="testResults"><strong id="testNumber">Test 1</strong> passed - date </p>';

var jsonDiv = document.createElement("div");
jsonDiv.innerHTML = jsonResult;
var content = document.getElementById("contentResult");
content.appendChild(jsonDiv);
var strongElement = document.getElementById("testNumber");
var strongCopy = $(strongElement).clone(true);
strongElement.parentNode.removeChild(strongElement);
var testResult = document.getElementById("testResults");
var testCopy = $(testResult).clone(true);
testResult.parentNode.removeChild(testResult);
jsonDiv.parentNode.removeChild(jsonDiv);
console.log(testCopy);
console.log(strongCopy);
于 2012-10-05T04:03:53.043 回答