Example of Jsonp principles and use of MVC

Source: Internet
Author: User
Tags to domain

 

Recently, json and jsonp have been used for work. The front-end is Android and the back-end is MVC. Generally, the following two formats are returned in the MVC Background: JSON and XML. Therefore, JSON is selected. JSONP is also used,

To put it simply, the principle of Jsonp is to use the <script> tag to introduce a js that defines json data, because the <script> tag is not subject to domain name restrictions, JSONP is a JSON-based form that can transmit data across domains.

Create an employee class

Company {; Conference {; Name {; Age {;View Code

Create a JsonpResult class that inherits the ActionResult.

In addition, the JavaScriptSerializer sequencer must apply the System. Web. Extensions assembly.

Obj {; CallbackName {; JsonpResult (obj,. Obj =. CallbackName = js = jsonp =. CallbackName ++ js. Serialize (. Obj) + =View Code

 

MVC background data settings:

MVC Controller Method

Public ActionResult ShopSetting ()
{

Employee e = new Employee ();
E. Age = 20;
E. Company = "Huawei ";
E. Conference = "year-end Conference ";
E. Name = "Janekim ";
Return GetJsonP (e, callback); // call the GetJsonP method and pass the Parameter

} // GetJsonP Method

Public ActionResult GetJsonP (object obj, string callback)
{
If (string. IsNullOrEmpty (callback) callback = "callback ";

Return new JsonpResult (obj, callback );

}

Return the following result:

Callback ({"Age": 20, "Company": "Huawei", Conference ":" year-end Conference "," Name ":" Janekim"})

 

Frontend call:

Function getUserInfo (checkUser ){
$. Ajax ({
Type: "GET ",
Url: "http: // xxx/employee/getjsonp? Callback =? ",
Cache: false,
Error: function (){
},
Jsonp: "callback ",
DataType: "jsonp ",
Success: function (result ){
CheckUser (result); // checkUser is a function for processing the employee object
}
});
}

If you want to see the simple implementation of the jsonp format, please see http://www.cnblogs.com/janekimyan/p/Janekim_Yan.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.