Using jquery $.ajax to PHP post GET values



我有一个我想传递一个值的php脚本。因此, example.com/test.php?command=apple。如果输入,则进行代码。所有这些都在服务器端效果,但是如何使用Ajax调用来完成此操作?

我的代码:

php:

<?php
if ($_GET['command']=='apples')
{
    //do code
    echo "hello";
}       
?>

jQuery:

$.ajax({
    url : '../command/test.php?command=apples'
}).done(function(data) {
    console.log("result: " + data);
});

下面的摘要非常简单,不言自明...但是,如果您有任何疑问,请随时使用本文下面的评论功能。 - )

jQuery:ajax ....

        var request = $.ajax({
            url         : "../command/test.php",
            data        : {"command": "apples"},
            dataType    : "json",
            type        : "POST"
        });
        request.done(function(data, textStatus, jqXHR){
            if(data){
                console.log(data);
            }
        });
        request.fail(function(jqXHR, textStatus) {
            alert( "Request failed: " + textStatus );
        });

php ....

<?php
    $response   = array();
    $command    = isset($_POST['command']) ? 
                  htmlspecialchars(trim($_POST['command'])) :
                  null;
    if($command){
        // BUILD UP YOUR RESPONSE HERE
        $response['command']  = $command;
        // ADD SOME ARBITRARY DATA - JUST FOR FUN
        $response['name']     = "Albert";
        $response['lastName'] = "Einstein";
     }
     die( json_encode($response) );

您可以将数据放入数据部分,我认为这将解决您的问题。

$.ajax({
    url : '../command/test.php',
    data: {command: "apples",login: "succes"}
}).done(function(data) {
    console.log("result: " + data);
});

另外,您可以看到自己得到的响应,打开开发人员工具,并且可以在network下看到您的请求时出现时,单击该请求,您可以看到响应。

您可以将POST请求中的值发送到php页面,并使用$.ajax

从那里获取返回的值

例如,我们将计算2个数字,并通过ajax

返回总和。

示例代码

$.ajax({
   url: "/path/to/page.php",
   type: "POST",
   data: {number_1: 10, number_2: 5},
   success: function(response){
      // alert $result from the php page which is called response here.
      alert(response);
   }
});

PHP页

// checking if data exists
if ($_POST['variable_1'] != null && $_POST['variable_2'] != null ){
    $variable_1 = $_POST['variable_1'];
    $variable_2 = $_POST['variable_2'];
    $result = $variable_1 + $variable_2;
}else{
    // either of the values doesn't exist
    $result = "No Data Was Sent !";
}
// returning $result which is either 15 or " no data was sent "
echo $result;

这将返回15。希望这是有道理的。

您需要发布。您可以使用url args或传递数据对象。

$.ajax({
    method: "POST",
    url: "../command/test.php",
    data: {
        command: "apples"
    }
})

您可以尝试这个

<script type="text/javascript">
        $.ajax({
            type: 'get',
            url: "../command/test.php",
            dataType: 'json',
            data: ({command: 'apples'}),
            success: function(data)
            {
                console.log("result: " + data);                           
            }
        });
</script>

最新更新