[英]Deserializing JSON from Controller to AJAX Success
I am having trouble finding the right format of using a HttpWebRequest
, and returning its response into readable JSON
for a Javascript AJAX function. 我很难找到使用
HttpWebRequest
的正确格式,并将其响应返回到Javascript AJAX函数的可读JSON
中。
If I return just text
, it adds escaping slashes to the response. 如果我只返回
text
,它将在响应中添加转义斜杠。 If I deserialize text
it then add's all the indentation and makes it unreadable by my Javascript. 如果我反序列化
text
,则添加所有缩进并使Javascript无法读取。 (I think because it is not passing an actual object either) (我认为是因为它也没有传递实际对象)
Just trying to pass a readable json object to my ajax. 只是试图将可读的json对象传递给我的ajax。
Controller 控制者
[HttpPost]
public ActionResult teamLookUp(string ID)
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("someurl.com/apis");
myReq.ContentType = "application/json; charset=utf-8";
var response = (HttpWebResponse)myReq.GetResponse();
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
var json2 = JsonConvert.DeserializeObject(text);
return Json(new { json = json2 });
// return Json(new {json = text}); returns json with escaping \'s
// i.e. "json":"{\"item":\"item2"}
// return Json(new {json = json2}); returns empty json,
// i.e. {"json":[[],[],[],[]]}
}
Javascript Java脚本
$.ajax({
url: "/Competitive/teamLookUp",
type: "POST",
data: "ID=" + ID,
success: function (json) {
alert(JSON.stringify(json));
alert(json[ID].name());
},
error: function(error) {
}
});
Need help with returning json object
back to my AJAX success function. 需要帮助将
json object
返回到我的AJAX成功函数。
use 采用
dynamic json2=JsonConvert.DeserializeObject(text);
instead of 代替
var json2 = JsonConvert.DeserializeObject(text);
hope that helps 希望能有所帮助
What kind of object are you trying to deserialize the response into? 您试图将响应反序列化为哪种对象? Right now it is just going into a string.
现在,它只是一个字符串。 Might want to create a object to deserialize the response from the service you are calling.
可能想创建一个对象,以反序列化正在调用的服务的响应。
Here is a working example to return a string object I came up with 这是一个返回我想出的字符串对象的工作示例
public ActionResult ReturnJson()
{
var someText = "some random text";
return Json(new {json = someText});
}
Javascript Java脚本
<script>
function testAjaxCall() {
$.ajax({
url: '@Url.Action("ReturnJson")',
type: "POST",
success: function (result) {
alert(result);
alert(result["json"]);
},
error: function (error) {}
});
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.