AJAX asynchronous request

Keywords: Javascript PHP JQuery xml JSON

Native ajax operations

  • JavaScript asynchronous GET request

    // Step 1: create an ajax object
    //Determine the browser type of the user and decide how to use ajax objects
    if (typeof ActiveXObject != "undefined") {
        var version = [
            'Msxml2.XMLHTTP.6.0',
            'Msxml2.XMLHTTP.5.0',
            'Msxml2.XMLHTTP.3.0',
            'Msxml2.XMLHTTP',
            'Microsoft.XMLHTTP'
        ];
        for (var i = 0; i <= version.length; i++) {
            try {
                var obj = new ActiveXObject(version[i]);
                if (typeof obj != "undefined") {
                    break;
                }
            } catch(ex) {
 
            }
        }
    } else {
        var obj = new XMLHttpRequest();
    }
    
    // Sense the ajax state. When the ajax state changes, the event onreadystatechange will be triggered
    obj.onreadystatechange = function(){
        // When the current status is 4, the data is received
        if (obj.readyState == 4 && obj.status == 200) {
            // Output response information
            alert(obj.responseText);
        }
    }
 
    // Set the information passed by GET
    var name = 'Xiao Ming';
    // Dealing with Chinese code disorder
    name = encodeURIComponent(name);
    // Step 2: create an HTTP request and set the "request address" and asynchronous request mode
    obj.open("get", "./test.php?fname=" + name + "&addr=beijing", true);
    // Step 3: send the request
    obj.send();
  • JavaScript asynchronous POST request

        // Creating Ajax objects
        //Determine the browser type of the user and decide how to use ajax objects
        if (typeof ActiveXObject != "undefined") {
            var version = [
                'Msxml2.XMLHTTP.6.0',
                'Msxml2.XMLHTTP.5.0',
                'Msxml2.XMLHTTP.3.0',
                'Msxml2.XMLHTTP',
                'Microsoft.XMLHTTP'
            ];
            for (var i = 0; i <= version.length; i++) {
                try {
                    var obj = new ActiveXObject(version[i]);
                    if (typeof obj != "undefined") {
                        break;
                    }
                } catch(ex) {
 
                }
            }
        } else {
            var obj = new XMLHttpRequest();
        }
        
        // Sense the Ajax state and trigger the event onreadystatechange when the Ajax state changes
        obj.onreadystatechange = function(){
            // When the current status is 4, the data is received
            if (obj.readyState == 4 && obj.status == 200) {
                // Output response information
                alert(obj.responseText);
            }
        }
 
        // Create an http request and set "request address" and asynchronous request mode
        obj.open("post", "./test.php");
        // Set HTTP header protocol information
        obj.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        var info = "fname=" + "Xiao Ming" + "&addr=beijing";
        // Send request
        obj.send(info);

JQuery Ajax operations

Download and import jQuery by yourself: < script SRC = ". / jQuery. Min.js" > < / script >

  • jQuery asynchronous GET request

// 1. Direct request
// $(function(){
//     $.ajax("./test.php", {
//         data:{name:"tom",age:23},
//         success:function(msg){
//             alert(msg);
//         }
//     });
// });
 
 
// 2. Configure setting parameter request
// $(function(){
//     $.ajax({
//         type:"GET",
//         url:"./test.php",
//         data:{name:"tom", age:23},
//         success:function(msg){
//             alert(msg);
//         }
//     });
// });
 
 
// 3. Preset global parameters through $. ajaxSetup() method
// $(function(){
//     //Preset global parameters
//     $.ajaxSetup({
//         type:"GET",
//         url:"./test.php",
//         data:{name:"tom",age:23},
//         success:function(msg){
//             alert(msg);
//         }
//     });
//     //Performing ajax operations, using global functions
//     $.ajax();
// });
 
// 4. Request with $. get() method
//Send get requests only
// $(function(){
//     $.get('./test.php');
// });
 
// Send a get request and accept the returned result
// $(function(){
//     $.get("./test.php", function(msg){
//         alert(msg);
//     });
// });
 
// Send request and pass data
// $(function(){
//     $.get("./test.php", {name:"tom",age:23}, function(msg){
//         alert(msg);
//     });
// });
 
// Send the get request and pass the data, accept the return result, and display the return format
// $(function(){
//     $.get("./test.php", {name:"tom",age:23}, function(msg){
//         alert(msg.name + " " + msg.age);
//     }, "json");
// });
 
// Use $. getJSON() to do the same
$.getJSON("./test.php", {name:"tom", age:23}, function(msg){
    alert(msg.name + " " + msg.age);
});
  • jQuery asynchronous POST request

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>jquery-ajax Send out post request</title>
</head>
<body>
 
<div>Ajax No refresh comments</div>
<ul>
    <li>Full name:<input type="text" id="input_name" /></li>
    <li>Commentary:<input type="text" id="input_comment" /></li>
</ul>
<input type="button" value="Comment" />
<table border="1"></table>
 
<script src="./jquery.min.js"></script>
<script>
// 1. Use $. post() method to send post request, the same as $. get()
// $(function(){
//     $.post("./comment.php", {name:'tom',age:23}, function(msg){
//         alert(msg.name + " " + msg.age);
//     }, "json");
// });
 
// 2. Use global ajax parameter to send post request
$(function(){
    // Set up global ajax
    $.ajaxSetup({
        url:"./comment.php",
        type:"POST",
        dataType:"json",
        success:comment_add
    });
    // Add button click event
    $(":button").click(comment_send);
    // Get default data
    $.ajax();
});
 
function comment_send(){
    var name = $("#input_name").val();
    var comment = $("#input_comment").val();
    // Submit and obtain data
    $.ajax({data:{name:name,comment:comment}});
}
 
function comment_add(data){
    html = "<tr><td>" + data.name + "</td><td>" + data.comment + "</td></tr>";
    $("table").append(html);
}
</script>
</body>
</html>

JQuery Ajax PHP cross domain request problem

  • The first method JSONP

Note: JSONP only supports get requests

1. First, add these two items to jQuery Ajax configuration parameters

    dataType: "jsonp",
    jsonp: "callback",

for example

        $.ajax({
            type: "GET",
            url: "http://127.0.0.1/ajax2/serverjsonp.php?number=" + $("#keyword").val(),
            dataType: "jsonp",
            jsonp: "callback",
            success: function(data) {
                if (data.success) {
                    $("#searchResult").html(data.msg);
                } else {
                    $("#searchResult").html(" error occurred: "+ data.msg);
                }
            },
            error: function(jqXHR){
               alert("An error occurred:" + jqXHR.status);
            },
        });

2. Then, make changes in php

$jsonp = $_GET["callback"];
echo $jsonp . '({"success":false,"msg":"Parameter error"})';  //The output string should be spliced with JSON
  • The second method XHR2

Note: other browsers support it, but IE must have more than IE10. Only the server interface and the following header information are required

header('Access-Control-Allow-Origin:*');  //Allow all access
header("Access-Control-Allow-Origin", "http://my.domain.cn:8080 "); / / only specific domain names are allowed to access
header('Access-Control-Allow-Methods:POST,GET');    //Methods that allow cross domain requests can be qualified
header('Access-Control-Allow-Credentials:true');    //Whether to bring cookie information when requesting

JavaScript Ajax requests xml data

xml example

<?xml version="1.0" encoding="UTF-8" ?>
<students>
    <student>
        <name>wendy</name>
        <age>35</age>
        <addr>Santa Fe</addr>
    </student>
    <student>
        <name>Yaphet</name>
        <age>32</age>
        <addr>Balchik</addr>
    </student>
    <student>
        <name>Isaiah</name>
        <age>35</age>
        <addr>Caldera</addr>
    </student>
</students>

js example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Ajax Obtain XML information</title>
    <script>
        function f1(){
            // Creating Ajax objects
            var obj = new XMLHttpRequest();
            // Sense Ajax state
 
            obj.onreadystatechange = function(){
                if (obj.readyState == 4 && obj.status == 200) {
                    // Get XMLDocument object
                    var xmlobj = obj.responseXML;
                    // Get the first element node students of xml object
                    var students = xmlobj.childNodes[0];
                    // Get all students' nodes under element node students
                    var student = students.getElementsByTagName('student');
                    // Traverse the student node and get specific information
                    var info = "";
                    for (var i = 0; i < student.length; i++) {
                        var name = student[i].getElementsByTagName('name')[0].firstChild.nodeValue;
                        var addr = student[i].getElementsByTagName('addr')[0].firstChild.nodeValue;
                        var age = student[i].getElementsByTagName('age')[0].firstChild.nodeValue;
                        // Concatenate output information string
                        info += "Full name:" + name + ",Address:" + addr + ",Age:" + age + "<br />";
                    }
                    // Write string to div string with id name result
                    document.getElementById('result').innerHTML = info;
                }
            }
 
            // Create an http request and set the request address
            obj.open("get", "./test.xml");
            //Send request
            obj.send();
        }
    </script>
</head>
<body>
    <h2>Ajax Obtain XML information</h2>
    <div id="result"></div>
    <input type="button" onclick="f1();" value="trigger" />
</body>
</html>

Posted by GM on Tue, 03 Dec 2019 22:03:45 -0800