Json显示为HTML文本 - 不是原始格式

时间:2013-01-07 18:40:17

标签: javascript json dojo

我正在尝试转换我必须在我的页面中显示为html文本的json数据,但是当它确实显示时它是json格式。因此,我想知道是否有可能消除所有括号等。有飞机html段落。

require(["dojo"], function (dojo){

dojo.ready(function(){
// Look up the node we'll stick the text under.
var targetNode = dojo.byId("licenseContainer");  


// The parameters to pass to xhrGet, the url, how to handle it, and the callbacks.
var xhrArgs = {
url: "",
handleAs: "text",
timeout : 2000,

load: function(data){
  // Replace newlines with nice HTML tags.
  data = data.replace(/\n/g, "<br>");

  // Replace tabs with spaces.
  data = data.replace(/\t/g, "&nbsp;&nbsp;&nbsp;");

  targetNode.innerHTML = data;
},
error: function(error){
  targetNode.innerHTML = "An unexpected error occurred: " + error;
}
}

 // Call the asynchronous xhrGet
 var deferred = dojo.xhrGet(xhrArgs);
});

});

目前json在我的页面上显示如下:

[{"Relevance":"Low","Name":"Clinton","id":1,,"Paragraph":Appointed secretary of state at the start of Mr Obama's first term, in January 2009, Mrs Clinton's health has been under intense scrutiny because she is considered a strong candidate for the Democratic nomination for president should she decide to run in 2016.}]

我能过滤或仅指定“段落”中的数据只是为了在html中显示吗?

任何建议或帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

您已将handleAs属性指定为“text”,这意味着您的响应将只是纯文本。这将使您难以从响应中解析出您想要的特定信息。将handleAs更改为json,以便将从服务器检索的信息转换为javascript对象。

handleAs:'json'

此时,您可以调用data ['Paragraph']或data.Paragraph。如果您想获得其他键/值对的值,则同样适用。如果你想要Relevance,你只需要打电话

alert(data.Relevance);

编辑: 另一件事,你的json看起来没有正确格式化,如果你有handleAs:'json'会导致错误。看起来应该是这样的

{"Relevance":"Low","Name":"Clinton","id":1,"Paragraph":"Appointed secretary of state at the start of Mr Obama's first term, in January 2009, Mrs Clinton's health has been under intense scrutiny because she is considered a strong candidate for the Democratic nomination for president should she decide to run in 2016."}