Detailed explanation of the method of calling python across domains from json

高洛峰
Release: 2017-01-13 13:01:17
Original
1130 people have browsed it

The example in this article describes the method of calling python across domains from json. Share it with everyone for your reference, the details are as follows:

Client:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
  <title>jQuery-跨域请求</title>
  <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
  <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
  </head>
   <script type="text/javascript">
  jQuery(document).ready(function(){
    $.ajax({
      type : "GET",
      url : "http://10.13.38.43:1234/?id=10&callback=?",
      dataType : "jsonp",
      jsonp: &#39;callback&#39;,
      success : function(json){
          alert(json.account);
        //$(&#39;#msg_box&#39;).html(json);
        //return true;
      }
    });
  });
  </script>
   <body>
  <div id="msg_box"></div>
  </body>
  </html>
Copy after login

Server

import web
urls=(&#39;/&#39;,&#39;Index&#39;,)
class Index:
    def GET(self):
      inputdata=web.input()
      mycallbackfun=inputdata.callback
      #return &#39;hello&#39; +inputdata.id
      return mycallbackfun+&#39;({"account":"XX","passed":"true","error":"null"})&#39;
app = web.application(urls, globals())
if __name__==&#39;__main__&#39;:
    app.run()
Copy after login

Attachment: Introduction to jquery cross-domain request method

Here Introduces the jQuery cross-domain request method and provides simple sample code for reference.

There was a problem with the use of ajax jsonp in the project: the request result could be obtained successfully, but the success method was not executed. Finally, it was solved and recorded.

function TestAjax()
{
  $.ajax({
    type : "get",
    async : false,
    url : "ajaxHandler.ashx", //实际上访问时产生的地址为: ajax.ashx?callbackfun=jsonpCallback&id=10
    data : {id : 10},
    cache : false, //默认值true
    dataType : "jsonp",
    jsonp: "callbackfun",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback)
    jsonpCallback:"jsonpCallback",
      //自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名
      //如果这里自定了jsonp的回调函数,则success函数则不起作用;否则success将起作用
    success : function(json){
      alert(json.message);
    },
    error:function(){
      alert("erroe");
    }
  });
}
function jsonpCallback(data) //回调函数
{
  alert(data.message); //
}
public class ajaxHandler : IHttpHandler
{
  public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = "text/plain";
    string callbackfun = context.Request["callbackfun"];
    context.Response.Write(callbackfun + "({name:\"John\", message:\"hello John\"})");
    context.Response.End();
  }
  public bool IsReusable {get {return false;}
}
Copy after login

ajax request parameter description:

dataType string The data type returned by the server.
If not specified, jQuery will automatically make intelligent judgments based on the HTTP package MIME information. For example, the XML MIME type is recognized as XML.

Available values:

"xml": Returns an XML document that can be processed with jQuery.
"html": Returns plain text HTML information; the included script tag will be executed when inserted into the dom.
"script": Returns plain text JavaScript code. Results are not cached automatically. Unless the "cache" parameter is set.

Note: When making remote requests (not under the same domain), all POST requests will be converted into GET requests. (Because the DOM script tag will be used to load)

"json": Returns JSON data.
"text": Returns a plain text string
"jsonp": jsonp format. When calling a function using jsonp format, when accessing the url, "callback=callbackFunName" will be automatically added to the end of the url to execute the callback function (callbackFunName).

jsonp string

Rewrite the name of the callback function in a jsonp request. This value is used to replace the "callback" part of the url parameter in a get or post request such as "callback=?". For example, jsonp:'callbackfun' will generate "callbackfun=?" and pass it to the server.

jsonpCallback String This parameter specifies a callback function name for the jsonp request.

This value will be used to replace the random function name automatically generated by jQuery. That is the question mark part in "callback=?" above.

This is mainly used to allow jQuery to generate unique function names so that requests are easier and callback functions and error handling can be conveniently provided.

You can also specify this callback function name when you want the browser to cache GET requests.

The main difference between ajax jsonp and ordinary ajax requests is the processing of request response results. The response result shown in the above code is:

jsonpCallback({ name:"world",message:"hello world"});
Copy after login

In fact, it is to call the jsonp callback function jsonpCallback, and pass the string or json to be responded to this method. Regarding the customized jsonp callback function, the success function It will not work, probably its underlying implementation (of course this is the default callback function, otherwise the success method will not be executed):

function default_jsonpCallback(data)
{
  success(data); //在默认的回调方法中执行
}
Copy after login

I hope this article will help everyone in Python programming. help.

For more detailed explanations on how to call python across json domains, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!