JQuery get and post methods pass value test and matters needing attention

  • 2020-03-30 03:41:46
  • OfStack

JQuery's get and post methods take three arguments: address, data, and callback function, but we know that addresses can also follow data (get_data.php? V1 =1&v2=2), and the second parameter can be omitted, that is, the second parameter can be directly written to the callback function, so what is the difference between the data written after the address and written in the data parameter?
Just a few experiments, take a look at the following code:
The following requires a reply

Jquery_data. PHP


echo "post: ";
print_r($_POST);
echo "get: ";
print_r($_GET);
?>

Jquery_test. HTML

Experiment 1:


$(function() {
//The post method has data in both places
$.post('jquery_data.php?v1=1', {v2: 2}, function(data) {
$('
').append(data).appendTo('body');
});
});

Return result:


post: Array
(
[v2] => 2
)
get: Array
(
[v1] => 1
)

Experiment 2:


$(function()
{
//Post method, data after the address, the second parameter is the callback function
$.post('jquery_data.php?v1=1', function(data)
{
$('<pre/>').append(data).appendTo('body');
});
});

Return the result, data in get:


post: Array
(
)
get: Array
(
[v1] => 1
)

Experiment 3:


$(function()
{
//Get method, using the data parameter to pass the value
$.get('jquery_data.php', {v2: 2}, function(data)
{
$('<pre/>').append(data).appendTo('body');
});
});

Return the result, data in get:


post: Array
(
)
get: Array
(
[v2] => 2
)

Experiment 4:


$(function()
{
//The get method, there's data in both places
$.get('jquery_data.php?v1=1', {v2: 2}, function(data)
{
$('<pre/>').append(data).appendTo('body');
});
});

Return the result, two data are merged, both in get:


post: Array
(
)
get: Array
(
[v1] => 1
[v2] => 2
)

Experiment 5:


$(function()
{
//Get method, with data in both places and the same variable name
$.get('jquery_data.php?v2=1', {v2: 2}, function(data)
{
$('<pre/>').append(data).appendTo('body');
});
});

Return the result, the data is in get, and the data in the data parameter overrides the data after the address:


post: Array
(
)
get: Array
(
[v2] => 2
)

From these simple examples, it is not difficult to see that the data after the address is always passed in the form of get, whether the get method or the post method is used; The data in the data parameter is passed according to the method.

Therefore, in order to avoid confusion, it is recommended that we try not to write the data after the address, but in the data parameters.

Of course, if you want to use the post method while using get to pass values, you can write the data to be passed in get after the address and the data to be passed in post in the data parameter.

In short, the method is dead, people are alive, how to use it depends on the actual situation. Practice is the sole criterion of truth. Do the experiment, master the knowledge more firmly.


Related articles: