ajax正确返回数据,却进入了error分支

.net 开发:

$.ajax({
        type: "POST",  //post没有数据量限制
        url: "ashx/PostHandle.ashx",
        data: { "datatype": "1", "event_name": event_name, "placename": placename, "starttimestamp": starttimestamp, "endtimestamp": endtimestamp }
        contentType: "text/plain; charset=utf-8",
        dataType: "json",   //必须
        beforeSend: function () {
            //$("#loading_bind")[0].style.visibility = "visible";
        },
        success: function (data) {
            alert('data');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("服务器响应提交失败,请重试...");
        },
        complete: function () {
            //$("#loading_bind")[0].style.visibility = "hidden";
        }
    });

后台ashx:

public void ProcessRequest (HttpContext context) {
        context.Response.Clear(); //清除所有之前生成的Response内容
        //context.Response.ContentType = "text/plain";
        StreamReader stream = new StreamReader(context.Request.InputStream);
        string xml = stream.ReadToEnd();  //post里面的数据
        XmlDocument doc = new XmlDocument();
        try {
            doc.LoadXml(xml);
        }
        catch(XmlException)
        {
            context.Response.Write("post加载的xml数据不能为空");
            return;
        }
        XmlElement root = doc.DocumentElement;
        string datatype = root.SelectSingleNode("datatype").InnerText;
        switch (datatype)
        {
            case "1"://添加线下活动促销
                if (AddEventPromotion(root).Equals("success"))
                { context.Response.Write("success"); }
                break;
            default:
                break;
        }
        context.Response.End();  
    }

后台返回数据全部正常,最后执行了:

context.Response.Write("success");

但js中缺执行了ajax的error分支,解决方法:
将js中ajax代码的第6行: dataType: "json", 注释掉 即可

详见datatype的说明 http://deony2jacob1314.iteye.com/blog/2017093

posted @ 2014-04-14 13:48  飞剑  阅读(1126)  评论(0)    收藏  举报