douxue7196 2018-01-17 18:26
浏览 155
已采纳

如何使用html id构建数组,然后在Javascript按钮onClick中将其作为JSON与ajax一起发送?

I am tying to use Post functions to send data from one php file to another, this is how my html code looks like (send.php):

    <!DOCTYPE html>
    <html>
    <head></head>
    <body>
    <p>operator:<input type="text" , id="operator"></p>
    <p>column:<input type="text" , id="columnName"></p>
    <button id="Btn">Click</button>
    <script src="js/jquery.min.js"></script>
    <script src="js/actions.js"></script>
    </body>
    </html>

This is how my JavaScript looks like (actions.js):

    $('#Btn').on('click', function () {
        var array = {'operator': $('#operator'), 'columnName': 
    $('#columnName')};
        $.ajax({
             url: 'receive.php',
             dataType: 'json',
             type: 'post',
             data: array,
             success: function (data) {
                if(data.success){
                     alert(data.operator);
                 } else {
                    alert("error");
                 }
             }

         });
     });

And this is what my receive.php code looks like:

    <?php
    header('Content-type: text/javascript');
    $json = array(
    'operator' => "",
    'columnName' => "",
     );
    if (isset($_POST['operator'],$_POST['columnName'])){
        $operator = $_POST['operator'];
        $columnName = $_POST['columnName'];

        $json['operator'] = $operator;
        $json['columnName'] = $columnName;
     }
     echo json_encode($json);
     ?>

When I fill both fields (column and operator) and I click on the button nothing happens! Any suggestions?

  • 写回答

1条回答 默认 最新

  • dongyan1993 2018-01-17 18:31
    关注

    firstly your html inputs are wrong it should be like

    <p>operator:<input type="text" id="operator"></p>
    <p>column:<input type="text" id="columnName"></p>
    

    should be separated by space only no comma(,).

    In JS use

     var array = {'operator': $('#operator').val(), 'columnName': 
    $('#columnName').val()};
    

    .val() to read the value of the input field

    also some changes in your php code the if() loop where you are checking for isset() only one input can be checked in isset() for another value you need to add && operator and another isset() to check for another input. here is the code

    if (isset($_POST['operator']) && isset($_POST['columnName'])){
        $operator = $_POST['operator'];
        $columnName = $_POST['columnName'];
    
        $json['operator'] = $operator;
        $json['columnName'] = $columnName;
        $json['success'] = TRUE;
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办