从JSON字符串使用jQuery解析HTML [英] Parsing HTML from a JSON String with jQuery
问题描述
我不知道什么即时做错了,但我有一个JSON字符串这一点:
I have no idea what im doing wrong, but I have a JSON string with this:
jsonp443489({"content":"<!DOCTYPE html><html><head><title>Title</title></head><body><p>Hello World</p></body></html>"});
我需要解析这是能够修改的内容。等,例如,标识要抢&LT; P&GT;
的含量
现在,jQuery的,如果我做的:
Now, in jQuery if i do:
console.log($(json.content).html());
它返回标题
。
如果我做的:
console.log($('p',json.content));
它返回 []
,或者空数组。
最后,如果我做的只是: 的console.log($(json.content));
Finally, if I do just: console.log($(json.content));
它返回 [&LT;冠军&GT;标题&LT; /标题&GT;,&LT; P&GT;的Hello World&LT; / P&GT;]
这很好,但我不能做 .find()
或任何东西。因为我不知道什么是HTML会,我不能使用 $(json.content)[1]
。
Which is fine, but then I cant do .find()
or anything. Since I wont know what the HTML will be, i cant use $(json.content)[1]
.
任何想法?
== ==更新
在这个黑客了几个小时,我决定尝试XML。我的示例XML是:
After hacking at this for a couple hours i decided to try XML. My example XML was:
<?xml version=\"1.0\" encoding=\"UTF-8\"?><doc><item>One</item><item>Two</item></doc>
这是给我同样的悲伤,然后打我,它的一个JS对象,而不是一个字符串和jQuery期待一个字符串。我去了,做了
It was giving me the same grief, then it hit me, its a JS object, not a string and jQuery is expecting a string. I went and did
$(JSON.stringify(json.content)).find('item')
和瞧!我得到了两个项目的数组。我是pretty的兴奋,但后来当我去,并试图再次使用HTML(使用JSONP返回HTML代码段以上):
And voila! I got an array of two items. I was pretty excited but then when I went and tried it with HTML again (using the JSONP return HTML snippet above):
console.log($(JSON.stringify(json.content)).find('p'));
我仍然得到一个空数组。它的驾驶我疯了...任何更多的想法?
I still get an empty array. It's driving me mad... Any more ideas?
推荐答案
有可能是一个更好的办法,但这样的作品(检索 P
元素):
There might be a better way, but this works (retrieves the p
elements):
$('<div />', {html: json.content}).find('p');
这篇关于从JSON字符串使用jQuery解析HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!