2012-01-16 19 views
5

Vấn đề của tôi đã được biết đến và thảo luận herehere. Nhưng ngay cả sau khi đọc và triển khai các giải pháp được đề xuất, tôi không thể thực hiện công việc này.gọi tên miền chéo với jQuery jsonp đến dịch vụ web ASP.NET

Vấn đề: các dịch vụ web trở xml insted của json:

<?xml version="1.0" encoding="utf-8"?> 
<string xmlns="http://tempuri.org/">"Now i am getting jsop string""2nd param"</string> 

Bây giờ cho phép phá vỡ các mã vào phần:

Remote Server (IIS 7.0, .NET 4):
web.config:

<?xml version="1.0"?> 
<configuration> 
     <system.webServer> 
      <modules> 
       <add name="JsonHttpModule.JsonHttpModule" type="JsonHttpModule"/> 
      </modules> 
     </system.webServer> 
    <system.web.extensions> 
     <scripting> 
      <webServices> 
       <jsonSerialization maxJsonLength="102400"/> 
      </webServices> 
     </scripting> 
    </system.web.extensions> 
    <system.web> 
     <compilation debug="true" targetFramework="4.0" /> 
     <customErrors mode="Off"/> 
     <webServices> 
      <protocols> 
       <add name="HttpGet"/> 
       <add name="HttpPost"/> 
      </protocols> 
     </webServices> 
    </system.web> 
</configuration> 


các dịch vụ web:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Services; 
using System.Web.Script.Services; 
using JsonHttpModule; 
/// <summary> 
/// Summary description for JSONP_EndPoint 
/// </summary> 
[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService] 
public class MyService : System.Web.Services.WebService { 
    [WebMethod] 
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] 
    public string Sum(string x, string y) 
    { 
     return x + y; 
    } 

} 


lớp HttpModule:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.IO; 
using System.Text; 

/// <summary> 
/// Summary description for ContentTypeHttpModule 
/// </summary> 
namespace JsonHttpModule 
{ 
    public class JsonHttpModule : IHttpModule 
    { 
     private const string JSON_CONTENT_TYPE = "application/json; charset=utf-8"; 

     public void Dispose() 
     { 
     } 
     public void Init(HttpApplication app) 
     { 
      app.BeginRequest += OnBeginRequest; 
      app.EndRequest += new EventHandler(OnEndRequest); 
     } 
     public void OnBeginRequest(object sender, EventArgs e) 
     { 
      HttpApplication app = (HttpApplication)sender; 
      HttpRequest request = app.Request; 
      //Make sure we only apply to our Web Service 
      if (request.Url.AbsolutePath.ToLower().Contains("MyService.asmx")) 
      { 
       if (string.IsNullOrEmpty(app.Context.Request.ContentType)) 
       { 
        app.Context.Request.ContentType = JSON_CONTENT_TYPE; 
       } 
       app.Context.Response.Write(app.Context.Request.Params["callback"] + "("); 
      } 
     } 
     void OnEndRequest(object sender, EventArgs e) 
     { 
      HttpApplication app = (HttpApplication)sender; 
      HttpRequest request = app.Request; 
      if (request.Url.AbsolutePath.ToLower().Contains("MyService.asmx")) 
      { 
       app.Context.Response.Write(")"); 
      } 
     } 
    } 
} 

Client Side (localhost):

<script> 
    $(function() { 
     $('#btn_test').click(function() { 
      $.ajax({ url: "http://tonofweb.com/MyService.asmx/Sum", 
       data: { x: JSON.stringify("Now i am getting jsop string"), y: JSON.stringify("2nd param") }, 
       dataType: "jsonp", 
       success: function (json) { 
        alert(json.d); 
       }, 
       error: function() { 
        alert("Hit error fn!"); 
       } 
      }); 
    }); 
}); 
</script> 
    <input id="btn_test" type="button" value="POST" /> 

vậy tôi đang làm gì sai ở đây? bạn có thể tự kiểm tra nó là một dịch vụ web trực tiếp. Cảm ơn sự giúp đỡ của bạn.

+0

thay đổi từ jsonp thành json không hoạt động do vấn đề miền chéo và chuyển đổi thành đối tượng vẫn trả về xml –

Trả lời

7

Dường như tất cả cấu hình và thuộc tính được đặt cho dịch vụ web để trả về JSON nhưng tôi đã thông báo trong yêu cầu jQuery của bạn, bạn không chỉ định loại nội dung của dữ liệu bạn đang chuyển. mã bên dưới:

$.ajax({ 
    url: "http://tonofweb.com/MyService.asmx/Sum", 
    contentType: "application/json; charset=utf-8", 
    data: { x: JSON.stringify("1"), y: JSON.stringify("2") }, 
    dataType: "jsonp", 
    success: function (json) { 
    alert(json.d); 
    }, 
    error: function() { 
    alert("Hit error fn!"); 
    } 
}); 

Thông báo Tôi đã thêm contentType: "application/json; charset=utf-8", vào cài đặt yêu cầu.

Tôi đã thử nghiệm mã này bằng cách duyệt tới http://tonofweb.com (mà trả về một 403 vào lúc này), bao gồm jQuery sử dụng jQuerify bookmarklet, và sau đó chạy mã từ câu hỏi của bạn đầu tiên (mà không contentType), và sau đó mã Tôi đã đăng ở trên (với contentType).

Dưới đây là các câu trả lời từ tab Mạng trong Công cụ nhà phát triển Chrome:

Without contentType:

<?xml version="1.0" encoding="utf-8"?> 
<string xmlns="http://tempuri.org/">"Now i am getting jsop string""2nd param"</string> 

Với contentType:

{"d":"12"} 

Vì vậy, một trong những thứ hai ít nhất kết quả trong JSON được trả về từ máy chủ. Vì vậy, tất cả những người khác bằng nhau, tôi muốn nói thêm contentType.

Xem ở đây để giải thích về các yêu cầu để trở về JSON:

ASMX and JSON – Common mistakes and misconceptions

Yêu cầu HTTP phải khai báo một content-type của application/json. Điều này thông báo cho ScriptService rằng nó sẽ nhận được các tham số của nó dưới dạng JSON và nó sẽ phản hồi bằng hiện vật.

Bây giờ bạn vẫn gặp sự cố khác và đó là yêu cầu, sau khi hoàn thành, gọi hàm lỗi. Nếu bạn thay đổi dataType: "jsonp" thành dataType: "json", nó sẽ gọi hàm thành công. Vì vậy, một cái gì đó về việc thực hiện của bạn gọi lại wrapper là sai, bởi vì jQuery không thể xử lý các phản ứng như JSONP.

Bây giờ tôi không thấy gọi lại được bọc trong các phản ứng một trong hai, cho JSONP, phản ứng nên một cái gì đó như:

jQuery17106476630216930062_1326752446188({"d":"12"}) 

tôi nhận thấy bạn đang liên kết đến this post về làm thế nào để làm một phản ứng JSONP từ một dịch vụ web, nhưng bạn không theo lời khuyên: bạn không sử dụng Response.Filter, thay vào đó bạn sử dụng Response.Write.

+0

vẫn không hoạt động .... –

+0

Có, nó đang hoạt động, bạn đã nói: "Sự cố: dịch vụ web quay lại xml insted của json: ". Tôi vừa thử nghiệm mã này và dịch vụ web của bạn phản hồi bằng JSON nếu bạn chỉ thêm 'contentType:" application/json; charset = utf-8 "' –

+1

tôi vẫn không thể làm việc này ngay cả sau khi tôi đã thêm contentType: "application/json; charset = utf-8 "tôi nhận được: " 1 "" 2 "