Using jquery for cross-domain request data

Source: Internet
Author: User

First, the server code is processed so that the returned data conforms to a specific format, so that PHP is used here.

The test.php code is as follows

1<?PHP2     $con=mysql_connect("localhost", "root", "root");3     mysql_select_db("Test",$con);4     5     $result=mysql_query("Select Username,password from User");6      while($row=Mysql_fetch_array($result)) {7         $com[] =$row;8     }9     Ten     $callback=$_get["Jsonpcallback"]; One     $json=json_encode ($com); A     Echo $callback.‘ (‘."$json".‘)‘; -?>

The output value of the $json is [{"0": "1", "username": "1", "1": "1", "Password": "1"},{"0": "admin", "username": "admin", "1": "1", " Password ":" 1 "}], is a standard JSON, but this page needs to handle cross-domain, so we need to wrap the JSON into callback ([{" 0 ":" 1 "," username ":" 1 "," 1 ":" 1 "," Password ":" 1 "},{" 0 ":" admin "," username ":" admin "," 1 ":" 1 "," Password ":" 1 "}]) format output to the browser

The HTML code is as follows

1 <!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd ">2 <HTML>3 <Head>4 <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8">5 <title>Insert Title here</title>6 <Scriptsrc= "Js/jquery.min.js"type= "Text/javascript"></Script>7 <Script>8 $(function(){9     varURL="http://localhost/test.php";Ten $.ajax ({ One Type:'GET', A Url:url, - DataType:'Jsonp', - Jsonp:'Jsonpcallback', the Success:function(data) { - Alert (json.stringify (data)); -     } -     }); + }); - </Script> + </Head> A </HTML>

Output results

Jsonp only supports "GET" requests, which is determined by the principle of loading cross-domain data, although jquery uses the $.ajax () function to get the data, but the JSONP to get the data is not Ajax, but the way to dynamically load JS.

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.