duan01203 2017-05-14 02:12
浏览 65
已采纳

如何使用ajax和PHP将数据传递到服务器? $ _POST ['data']不起作用

I have an HTML form that I want to send to the server (using a PHP script) some information before it gets submitted. I'm using .ajax() jQuery function as well.

Here's my demo.html file:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="form-group">
<label>Provincia</label>
<select id ="demo" class="form-control">
<option> </option>
<option value="op1">Opcion 1</option>
<option value="op2">Opcion 2</option> 
<option value="op3">Opcion 3</option> 
</select>
</div>

<div id="demo2"></div>

<script>

$(document).ready(function() {
    $('#demo').on('change', do_something);
    console.log('ready');
});

function do_something() {
    var selected = $('#demo').val();
    $.ajax({
        url:        'delete.php',
        type:       'POST',
        dataType:   'json',
        data:       { selected }
    });
    console.log(selected);
    $('#demo2').append(selected);
}
</script>

I don't know what to do to get the selected item. I get to print the selected item on the screen and in the console. How do I get that with PHP?

The delete.php file has only this:

<?php
var_dump($_POST['data']);
var_dump($_POST['selected']);

Because I want to know what's on the server, but nothing gets printed. How may I get what's been selected?

  • 写回答

2条回答 默认 最新

  • dongyuji7309 2017-05-14 02:38
    关注

    Use data attribute to set values you want to send to PHP and you can also set success to execute code when the request is successful.

    function do_something() {
        var selected = $('#demo').val();
        $.ajax({
            url:        'delete.php',
            type:       'POST',
            dataType:   'json',
            data:       { selected: selected },
            success: function (response) {
                // response comes from PHP
                if (response.result == true) {
                    // request was success
                }else if (response.result == false) {
                    // request was not successful
                }
            }
        });
    }
    

    Then in your PHP, you can access the values through $_POST

    <?php
    
    $selected = $_POST['selected'];
    
    // rest of the code here
    // you can also send response to Javascript here
    // for failure echo json_encode(['result' => false]);
    // for success echo json_encode(['result' => true])
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug