0

我目前正在尝试转换我必须在我的页面中显示为 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 中?

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

4

1 回答 1

0

您已将 handleAs 属性指定为“文本”,这意味着您的响应将只是纯文本。这将使从响应中解析出您想要的特定信息变得困难。将 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."}
于 2013-01-07T18:56:13.610 回答