JSONP不使用.NET webservice并返回html

时间:2014-08-10 18:42:41

标签: jquery asp.net web-services asp.net-ajax jsonp

我为返回字符串数据创建了简单的web服务。这是default.aspx页面中的代码

[System.Web.Services.WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void login(string name)
{

    StringBuilder sb = new StringBuilder();
    JavaScriptSerializer js = new JavaScriptSerializer();
    sb.Append("Callbabk(");
    //sb.Append(js.Serialize(name));
    sb.Append("{\"response\":\"testdata\"}");
    sb.Append(");");

    Context.Response.Clear();
    Context.Response.ClearHeaders();
    Context.Response.ClearContent();
    Context.Response.CacheControl = "no-cache";
    Context.Response.Expires = -1;
    Context.Response.ContentType = "application/json; charset = utf - 8";
    Context.Response.Charset = "utf=8";
    Context.Response.ContentEncoding = Encoding.UTF8;
    Context.Response.Write(sb.ToString());
    Context.Response.Flush();
    Context.Response.Close();
    Context.Response.End();        
}

另请参阅我为访问上述远程Web服务而创建的jquery ajax函数。

              function checkfun(){

                $.ajax({                
                    //crossDomain: true,
                    contentType: "application/json; charset=utf-8",
                    type: "POST",
                    url: "http://remoteIPaddress/Default.aspx/login",
                    data: { name: "datatest" },                        
                    dataType: "jsonp",  
                    jsonp: 'jsonp_callback',
                    success: OnSuccess,
                    error: function (response) {
                        alert('test:'+response);                            
                    }
                });

             }
             function OnSuccess(response) {
               alert(response.d);
             }

当我在Google Chrome网络中看到ajax调用时,它会显示状态200 OK,但作为响应,它显示了html和ajax错误函数被引发。同样在控制台中显示错误'资源被解释为其他,但转移时MIME类型未定义。'。所以,请让我知道为什么我没有得到回应并得到这样的错误。

1 个答案:

答案 0 :(得分:0)

对于跨域JSONP,最快的是使用处理程序

<强> Handler.ashx

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {

        var name = context.Request.QueryString["name"];
        var callback = context.Request.QueryString["callback"];

        var data = new { response = "name is " + name  };
        var js = new System.Web.Script.Serialization.JavaScriptSerializer();

        context.Response.ContentType = "application/json; charset=utf-8";
        context.Response.Write( callback + "("+ js.Serialize(data) + ")" );
        context.Response.End();        
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

并致电 JS

$.ajax({
    type: "GET",
    url: "Handler.ashx",
    data: { name: "test" },
    dataType: "jsonp",
    success: function (json) {
        alert(json.response);
    },
    error: function (response) {
        alert('error:' + response);
    }
});