Pregunta

This is very simple.I think i may be having an issue with incompatible response content type

This is the code i am using to send a jQuery ajax request:

 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);

and this is the response i am trying to fetch in success callback.

{
  '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 &quot;Arial&quot;" 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': ''
}

But success is not fired.I am setting context.Response.ContentType = "application/json"; in the server side request handler and am simply writing the above string to response.Whats the correct way to do this?

EDIT:

returning it this way:

 return "{'name':'" + name + @"',
                'svg1':'" + dt.Rows[0]["svg1"].ToString() + @"',
                'svg2':'" + dt.Rows[0]["svg2"].ToString() + "'}";

This worked:

 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();
¿Fue útil?

Solución

Your problem is not in your JavaScript code or in your jQuery API usage. Like others have pointed out it is in the server side. More specifically, JSON object keys have to be double quotes (and more generally JSON strings have to be double quoted).

As you are using C# and ASP.NET from the code you posted. You have alternatives depending on what framework you're using. In All cases, I suggest you use an object instead of building the JSON yourself.

var yourObj = new {name=name,svg1=dt.Rows[0]["svg1"].ToString(),svg2=dt.Rows[0]["svg2"].ToString()}

Now you have a C# object representing your data.

If you're using something like ASP.NET MVC:

return Json(yourObj,JsonBehavior.AllowGet);

If you're using WebAPI you can just do

return yourObj; // will figure out JSON conversion itself

If you're using anything else, or whatever you're using does not support JSON responses itself. You need to get the Newtonsoft.JSON package from NuGet and return:

return JsonConvert.SerializeObject(yourObj);

Which will convert your object to a string validly.

Otros consejos

You should create a strong typed object for return type and then convert it to JSON.

public class Template
{
    public string Name {get; set;}
    public string SvgXml1 {get; set;}
    public string SvgXml2 {get; set;}
}

then in your server side .ashx:

var template = new Template 
{
    Name = name,
    SvgXml1 = dt.Rows[0]["svg1"].ToString(),
    SvgXml2 = dt.Rows[0]["svg2"].ToString()
};

return JsonConvert.SerializeObject(template);

and finally in your success callback function:

var name = data.Name;
var svg1 = data.SvgXml1;
...
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top