Python Learning---jsonp learning 180130

Source: Internet
Author: User

Homologous policy mechanism

Origin: protocol://IP: Port " protocol, domain name, port same "

cross-domain: know the other side of the interface, and the data returned by the other party must also be in JSONP format

Problem Description: Ajax requests data across domains, the actual browser has already got the data, but the browser because of the same-origin policy hides the content, do not show us the data. In other words, Ajax cannot request data across domains.

Problem solving: <script src= "" >

tags with src attributes can request data across domains, which is why IMG can refer to images from other sites

Jsonp's prototype: create a callback function and invoke the function on the remote service and pass the JSON data as a parameter to complete the callback.

Jsonp must be a GET request

JSONP Instance one: Using the SRC attribute of the script tag

padding: Is the function that puts the data inside the function and then packages it to the foreground,

Cons: There must be a function in the foreground script that handles a write function, because the essence is to use the function to receive parameters

Correctly add script tags and content dynamically

settigs.py:

' DIRS ': [Os.path.join (Base_dir, ' templates ')],  # Set templates path to Django previous version # ' DIRS ': [],      # comment out the line, this is the Django 2.0.1 Latest Version # ' Django.middleware.csrf.CsrfViewMiddleware ',         ... Omit default configuration Static_url = '/static/' Template_dirs = (Os.path.join (base_dir,  ' templates '),)  # original config # static resource file Staticfiles _dirs = (Os.path.join (base_dir, "statics"),)   # Now add the configuration, here is the tuple, note the comma

Templates/ajax_jquery.html

<! DOCTYPE html>

mysite2/urls.py

From Django.contrib import adminfrom django.urls import pathfrom Blog import viewsfrom django.conf.urls import Urlurlpatte RNS = [      # jquery_ajax  url (r ' ajax-jquery/', views.ajax_jquery),  # jquery_ajax_test  url (r ' Jquery_ajax _test/', views.jquery_ajax_test),]

views.py

From django.shortcuts import Render, httpresponse# Jquery-to-ajaxdef ajax_jquery (Request):    return Render ( Request, ' ajax_jquery.html ') # jquery-to-ajaximport jsondef jquery_ajax_test (Request):    print (' request. POST ', request. POST)    # return HttpResponse (' Hello ')   # error, at this time cross-domain return to scrip label an undefined hello variable     # return HttpResponse (' var hello ')   # Correct, at this time cross-domain return to scrip label a definition but no content of the Hello variable    return httpresponse (' Test ("" Hello ")

Page display:

Dynamically create a Jsonp instance of the script:

settigs.py:

' DIRS ': [Os.path.join (Base_dir, ' templates ')],  # Set templates path to Django previous version # ' DIRS ': [],      # comment out the line, this is the Django 2.0.1 Latest Version # ' Django.middleware.csrf.CsrfViewMiddleware ',         ... Omit default configuration Static_url = '/static/' Template_dirs = (Os.path.join (base_dir,  ' templates '),)  # original config # static resource file Staticfiles _dirs = (Os.path.join (base_dir, "statics"),)   # Now add the configuration, here is the tuple, note the comma

Templates/ajax_jquery.html

<! DOCTYPE html>

mysite2/urls.py

From Django.contrib import adminfrom django.urls import pathfrom Blog import viewsfrom django.conf.urls import Urlurlpatte RNS = [      # jquery_ajax  url (r ' ajax-jquery/', views.ajax_jquery),  # jquery_ajax_test  url (r ' Jquery_ajax _test/', views.jquery_ajax_test),]

views.py

From django.shortcuts import Render, httpresponse# Jquery-to-ajaxdef ajax_jquery (Request):    return Render ( Request, ' ajax_jquery.html ') # jquery-To-ajaxdef jquery_ajax_test (Request):    print (' request. GET ', request. GET)    func = Request. Get.get (' callbacks ', None)    print (' func; ', func)    return HttpResponse ("%s (' World ')"% func)

Page display:

Attention:

There are 2 environments running: Python manage.py runserver 8081

The project itself is: http://127.0.0.1:8080/ajax-jquery/

The realization of jquery to Jsonp

1. Name of the callback function defined with jquery:

$.getjson ("http://127.0.0.1:8081/jquery_ajax_test?callback=?", function (ARG) {    Console.log ("successfully, Hello "+ arg)});

Note that you must add a callback parameter after the URL so that the Getjson method knows to access the service Jsonp, and the question mark behind the callback is the name of a callback function that is automatically generated internally.

2. Use a custom Function name:

Form One: Custom Function + Call the specified function "not recommended" functions Sayhi () {      ...} $.ajax ({    URL: "Http://127.0.0.1:8002/get_byjsonp",    dataType: "Jsonp",  # requires the server to return data in a JSONP format, A function is nested in a data form, otherwise returning the original type    JSONP: ' Callback ',    jsonpcallback: ' Sayhi '}); Note: Jsonp: ' Callback ' + Jsonpcallback: " Sayhi "  --piecing together a key-value pair to send past---->  ' callback ': ' Sayhi ' form two: Custom function + do not specify  " recommended "$.ajax ({    URL:"/http 127.0.0.1:8002/get_byjsonp ",    dataType:" Jsonp ",            //must have, tell the server that this visit is going to be a jsonp result.    Jsonp: ' Callback ',          //jquery help randomly generated: callback= "Wner"    success:function (data) {  # Receive the data from the background to be sent to        alert (data)     });

Getjson of function names defined with jquery--instances

settigs.py:

' DIRS ': [Os.path.join (Base_dir, ' templates ')],  # Set templates path to Django previous version # ' DIRS ': [],      # comment out the line, this is the Django 2.0.1 Latest Version # ' Django.middleware.csrf.CsrfViewMiddleware ',         ... Omit default configuration Static_url = '/static/' Template_dirs = (Os.path.join (base_dir,  ' templates '),)  # original config # static resource file Staticfiles _dirs = (Os.path.join (base_dir, "statics"),)   # Now add the configuration, here is the tuple, note the comma

Templates/ajax_jquery.html

<! DOCTYPE html>

mysite2/urls.py

From Django.contrib import adminfrom django.urls import pathfrom Blog import viewsfrom django.conf.urls import Urlurlpatte RNS = [      # jquery_ajax  url (r ' ajax-jquery/', views.ajax_jquery),  # jquery_ajax_test  url (r ' Jquery_ajax _test/', views.jquery_ajax_test),]

views.py

From django.shortcuts import Render, httpresponse# Jquery-to-ajaxdef ajax_jquery (Request):    return Render ( Request, ' ajax_jquery.html ') # jquery-To-ajaxdef jquery_ajax_test (Request):    print (' request. GET ', request. GET)    func = Request. Get.get (' callback ', None)    print (' func; ', func)    return HttpResponse ("%s (' World 2020 ')"% func)

Page display:

Getjson of use a custom function name--instance:

settigs.py:

' DIRS ': [Os.path.join (Base_dir, ' templates ')],  # Set templates path to Django previous version # ' DIRS ': [],      # comment out the line, this is the Django 2.0.1 Latest Version # ' Django.middleware.csrf.CsrfViewMiddleware ',         ... Omit default configuration Static_url = '/static/' Template_dirs = (Os.path.join (base_dir,  ' templates '),)  # original config # static resource file Staticfiles _dirs = (Os.path.join (base_dir, "statics"),)   # Now add the configuration, here is the tuple, note the comma

Templates/ajax_jquery.html

<! DOCTYPE html>

mysite2/urls.py

From Django.contrib import adminfrom django.urls import pathfrom Blog import viewsfrom django.conf.urls import Urlurlpatte RNS = [      # jquery_ajax  url (r ' ajax-jquery/', views.ajax_jquery),  # jquery_ajax_test  url (r ' Jquery_ajax _test/', views.jquery_ajax_test),]

views.py

From django.shortcuts import Render, httpresponse# Jquery-to-ajaxdef ajax_jquery (Request):    return Render ( Request, ' ajax_jquery.html ') # jquery-To-ajaxdef jquery_ajax_test (Request):    print (' request. GET ', request. GET)    func = Request. Get.get (' callback ', None)    print (' func; ', func)    return HttpResponse ("%s (' World 2020 ')"% func)

Page display:

. The specified function of the Ajax cross-domain request

settigs.py:

' DIRS ': [Os.path.join (Base_dir, ' templates ')],  # Set templates path to Django previous version # ' DIRS ': [],      # comment out the line, this is the Django 2.0.1 Latest Version # ' Django.middleware.csrf.CsrfViewMiddleware ',         ... Omit default configuration Static_url = '/static/' Template_dirs = (Os.path.join (base_dir,  ' templates '),)  # original config # static resource file Staticfiles _dirs = (Os.path.join (base_dir, "statics"),)   # Now add the configuration, here is the tuple, note the comma

Templates/ajax_jquery.html

<! DOCTYPE html>

mysite2/urls.py

From Django.contrib import adminfrom django.urls import pathfrom Blog import viewsfrom django.conf.urls import Urlurlpatte RNS = [      # jquery_ajax  url (r ' ajax-jquery/', views.ajax_jquery),  # jquery_ajax_test  url (r ' Jquery_ajax _test/', views.jquery_ajax_test),]

views.py

From django.shortcuts import Render, httpresponse# Jquery-to-ajaxdef ajax_jquery (Request):    return Render ( Request, ' ajax_jquery.html ') # jquery-To-ajaxdef jquery_ajax_test (Request):    print (' request. GET ', request. GET)    func = Request. Get.get (' callback ', None)    return HttpResponse ("%s (' World 2020 ')"% func)   # func is [] because no call is needed at all, the foreground is defined

Page display:

Python Learning---jsonp learning 180130

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.