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 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了