这很简单。我想我可能遇到响应内容类型不兼容的问题
这是我用来发送 jQuery ajax 请求的代码:
var settings = { dataType: 'json',
url: 'services/loadTemplate.ashx',
data: JSON.stringify({ 'Name': element.name }), // element.name },
processData: false,
//contentType: "application/json; charset=utf-8",
type: 'POST',
success: function (data) {
console.log('successData:'+data);
alert(data);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
}
$.ajax(settings);
这是我试图在success
回调中获取的响应。
{
'name': 'sMan',
'svg1': '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="513" height="490"><desc>Created with Raphaël</desc><defs></defs><text x="50.5" y="50" text-anchor="middle" font="10px "Arial"" stroke="none" fill="#000000" font-size="0px" style="text-anchor: middle; font-style: normal; font-variant: normal; font-weight: normal; font-size: 0px; line-height: normal; font-family: Arial;"><tspan>Text</tspan></text><image x="173.5" y="79.5" width="176" height="158" preserveAspectRatio="none" xlink:href="uploaded/75884f70-8872-49c1-8337-2cbbca626b2e.png" id="P28m" fill="#ff0000" stroke="#000000" stroke-width="1" fill-opacity="1" stroke-opacity="1" font-family="Calibri" style="stroke-width: 1px; fill-opacity: 1; stroke-opacity: 1; font-family: Calibri;"></image></svg>',
'svg2': ''
}
但是没有触发成功。我 context.Response.ContentType = "application/json";
在服务器端请求处理程序中进行设置,只是将上面的字符串写入响应。正确的方法是什么?
编辑:
以这种方式返回:
return "{'name':'" + name + @"',
'svg1':'" + dt.Rows[0]["svg1"].ToString() + @"',
'svg2':'" + dt.Rows[0]["svg2"].ToString() + "'}";
这有效:
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
// jsonWriter.WriteStartArray();
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("name");
jsonWriter.WriteValue(name);
jsonWriter.WritePropertyName("svg1");
jsonWriter.WriteValue(dt.Rows[0]["svg1"].ToString());
jsonWriter.WritePropertyName("svg2");
jsonWriter.WriteValue(dt.Rows[0]["svg2"].ToString());
jsonWriter.WriteEndObject();
/* return "{'name':'" + name + @"',
'svg1':'" + dt.Rows[0]["svg1"].ToString() + @"',
'svg2':'" + dt.Rows[0]["svg2"].ToString() + "'}";*/
}
return sb.ToString();