There are two most common ways for the client to pass parameters: Post GET

Therefore, front-end and back-end interactions can be classified as follows:

1. Enter a GET request in the address bar of the browser. You can url concatenate data directly in AjaxCopy the code
/ / url value
 url: "TestJsonServlet? id="+id+"&gender="+"Male".// The path of price increase
Copy the code
2. Hyperlink A: Must be a GET request;Copy the code
// Submit data via the href attribute of the a tag, similar to that of js.
<a href="DeleteUserServlet? Id = '3' & gender = "male" "></a>
Copy the code
3.JS submits the data through the specified path window.location.href.Copy the code
var deleteUser = function (deleteId) {
        if (confirm("Confirm deletion number is ["+deleteId+A member of "]?")) {window.location.href="DeleteUserServlet? deleteId="+deleteId; }}Copy the code
4. Form: can be GET or POST, depending on the method value of <form>;Copy the code
// The form submits all the contents of the form to the background, such as input fields, checkboxes, checkboxes, text fields, file fields, etc.
//1. In the background, the corresponding value can be obtained through the corresponding name attribute.
//2. The action attribute in the from form identifies the address of the submitted data.
//3. The method attribute specifies how the form is submitted.
<form action="demo.do" method="post"> User name: <br>< input type="text" name="username"><br> Password :<br> <input type="password" name="password" Type ="submit" value=" submit" > </form>Copy the code
5. Img can send get requests, but can only be displayed in the form of pictures; 6. Use link to send GET requests, but only in the form of CSS, favicon display;Copy the code

7.JQuery ajax()

JavaScript also has Ajax submissions, but there’s too much code, so JQuery simplifies AJAX in JS. Import the corresponding JQuery package to use. The general format is:

.ajax({
            url: "TestJsonServlet".// The path of price increase
            type: "post".// Submission method
            data: {
                // Data submitted to the background
            },
            dataType: "JSON".// Specifies the data to return after a successful request
            success: function (data) {
                // The method is entered after the request succeeds, and data is the data returned after the request succeeds
            },
            error: function (errorMsg) {
                ErrorMsg is the error message returned after the request fails}});Copy the code

8.JSONP

The JSON namely “JSON Padding”

Get requests can be made with script, but they can only be executed as scripts.

When the websites www.a.com and www.b.com need to be accessed, script can be used as the interaction mode

Similarly, JSONP requests introduced with JQuery are much simpler

Requestor method 1: Ajax ()


$.ajax({
    url: 'http://b.com/?callback=' + functionName,
    dataType: 'jsonp'.success: function(response) {
       if(response === 'success') {// The function to execute on success...}}})Copy the code

JQuery uses JSONP


<script>
$.getJSON("https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=?".function(data) {
    // Pass the callback function jsonCallback with data to the responder
    var html = '<ul>';
    for(var i = 0; i < data.length; i++)
    {
        html += '<li>' + data[i] + '</li>';
    }
    html += '</ul>';
    
    $('#divCustomers').html(html); 
});
</script>
Copy the code

Requestor written before simplification

First: pure JS writing (creating script tags from JS)

<script>
    button.addEventListener(
        'click'.(e) = > {
            / / the first step
            /* The requestor (front end of a.com) defines a function f to be executed after a successful/failed request is usually named using random numbers (the callback function, i.e. the user provides a function to the other party to call) */
            // randomly generate the callback functionName and create the callback function functionName(result)
            let functionName = 'x' + parseInt(Math.random() * 10000.10) 
            window[functionName] = function(result) {
                if (result === 'success') {
                    // What to do after taking the callback argument...}}/ / the second step
            /* The requester dynamically creates a script (added to the body) whose SRC points to the responder URL (b.com back end) and passes the callback function name as an argument, namely http://b.com?callback=f */
            let script = document.createElement('script')
            // Send the request to get the script, passing the callback function functionName
            script.src = 'http://y.com/?callback=' + functionName    
            // Add the script to the body automatically
            document.body.appendChild(script)    
            
            // Destroy after execution to avoid polluting the namespace; And the script is removed from the page on success/failure;
            script.onload = function(e) {
                e.currentTarget.remove()
                delete window[functionName]
            }
            script.onerror = function(e) {
                e.currentTarget.remove()
                delete window[functionName]
            }
        }
    )
</script>
Copy the code

Second: HTML + JS writing method

<script type="text/javascript">
function callbackFunction(result, methodName)
{
    // The result can be rendered
    var html = '<ul>';
    for(var i = 0; i < result.length; i++)
    {
        html += '<li>' + result[i] + '</li>';
    }
    html += '</ul>';
    document.getElementById('divCustomers').innerHTML = html;
}
</script>
// Create a connection
<script type="text/javascript" src="https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script>
Copy the code

Responder node. Js

if (path === '/' && method === 'GET') {
    response.setHeader('Content-Type'.'application/javascript')
    response.write('// The responder receives the request, constructs the JavaScript code string that calls this function according to the query parameter f and the returned data // such as f.call(undefined, data) or f(data) as the response result returned to the requester;${query.callback}.call(undefined, 'success')
    `)
    response.end()
}
Copy the code

Summary: If the post submission mode is not specified, the default submission mode is GET. In addition, a URL in Ajax can be concatenated directly with strings and then submitted to the background as a GET submission.