0

问题是控制器可以提供 json 或 html 片段。怎么知道它是什么?

$(document).on("submit", "form.client-form", function () {
    $.ajax({
        type: this.method,
        url: this.action,
        data: $(this).serialize(),
        success: function (result) {
            if (result is json) { 
                ... 
            } else if (result is html) {
                $("#result").html(result);
            }
        }
    });
});
4

3 回答 3

2

另一个解决方案...在这里找到:jquery how to check response type for ajax call

$(document).on("form.client-form", "submit", function () {
    $.ajax({
        type: this.method,
        url: this.action,
        data: $(this).serialize(),
        success: function(result, status, xhr){ 
            var ct = xhr.getResponseHeader("content-type") || "";
            if (ct.indexOf('html') > -1) {
                //html here
                $("#result").html(result);
            }
            if (ct.indexOf('json') > -1) {
                //json here
            } 
        }
    });
});  
于 2013-05-20T14:27:26.393 回答
0
$(document).on("form.client-form", "submit", function () {
    $.ajax({
        type: this.method,
        url: this.action,
        data: $(this).serialize(),
        success: function (result) {
            try {
                var response = $.parseJSON(result); 
            }
            catch (ex){
                //something else
                $("#result").html(result);
            }
        }
    });
});
于 2013-05-20T14:00:08.190 回答
0

使用转换器怎么样?看看在 jquery ajax api 上使用转换器:http: //api.jquery.com/jQuery.ajax/

于 2013-05-20T14:02:20.450 回答