wen tian
wen tian

Reputation: 441

How to get the JSON value of the iframe?

I am trying to get the iframe's document object, but I don't seem to write it right, I don't know how to get the value of json.

My picture: enter image description here

My code:

var iframe = document.getElementById("myframe");

var pre_info = iframe.contentDocument.document.getElementsByTagName("pre")[0].innerHTML;
var item_info = JSON.parse(pre_info);

console.log("object", pre_info);

Upvotes: 1

Views: 3487

Answers (2)

Parth Patel
Parth Patel

Reputation: 824

For browser compatibility use contentWindow with contentDocument(some time not supported).

Below code may solve your problem.

var iframe = document.getElementById("myframe");
var y = (iframe.contentWindow || iframe.contentDocument);
var pre_info = y.document.getElementsByTagName("pre")[0].innerHTML;
var item_info = JSON.parse(pre_info.slice(1, -1));
console.log("object", pre_info);

Upvotes: 1

Secant
Secant

Reputation: 11

"{"code":"400","msg":"","data":""}"(including the wrapper double quotes) in the pre tag is not a ready-to-parse string, you should slice it with .slice(1, -1) to remove the double quotes and then parse it to JSON.

Upvotes: 0

Related Questions