dqyat62284 2018-06-29 04:15
浏览 59
已采纳

如何使用ajax将数据传递给php?

I want to display a message according to the className passed to server using AJAX . I'm new ajax , I have no idea about that..

myhtml code :

<div class="header">
        <h2>Configuration</h2>
        <p> Enable: </p> <i class="fas fa-toggle-off " id="enable-btn"></i>
        <span id="demo">Dashboard Enabled</span>
    </div>

myJS code :

function enableButtonClicked() {
    $(document).ready(function () {
        $('#enable-btn').click(function () {
            $( ".dashboard, #demo" ).toggle();
            $(this).toggleClass("fa-toggle-off fa-toggle-on");
        });
    }); 
}

ajax code :

function displayMessageAccordingToButtonState() {
    var x = document.getElementById('enable-btn').className;
    if( x == 'fas fa-toggle-off'){
        var msg = "Button Disabled"
        $('.header').load('request.php',{"displayMsg":msg});
    }
    else {
        var msg = "Button Enabled"
        $('.header').load('request.php',{"displayMsg":msg});
    }

}

php code :

<?php
   if( $_REQUEST["displayMsg"] ){
      $msg = $_REQUEST['displayMsg'];
      echo "".$msg ;
   }
?> 
  • 写回答

3条回答 默认 最新

  • dongyu4455 2018-06-29 05:25
    关注

    this is working demo

    just copy and try

    i have added extra span and ajax file content is copy to that content

     <html>
          <head>
          <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
          </head>
          <body>
    
          <div class="header">
             <h2>Configuration</h2>
             <p> Enable: </p> <i class="fas fa-toggle-off " id="enable-btn"></i>
             <span id="demo">Dashboard Enabled</span>
         </div>
        <span id="demo2"></span>
          </body>
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">          </script>
     <script>
    $(document).ready(function () {
        $('#enable-btn').click(function () {
            $( ".dashboard, #demo" ).toggle();
            $(this).toggleClass("fa-toggle-off fa-toggle-on");
        });
    }); 
    
    
     $('#enable-btn').click(function () {   
     var x = document.getElementById('enable-btn').className;    
     if( x == 'fas fa-toggle-off'){
        var msg = "Button Disabled"
        $('#demo2').load('request.php',{"displayMsg":msg},function(responseTxt,      statusTxt, xhr){
        if(statusTxt == "success")
            console.log("External content loaded successfully!"+responseTxt);
        if(statusTxt == "error")
            console.log("Error: " + xhr.status + ": " + xhr.statusText);
    });
    }
    else {
        var msg = "Button Enabled"
                $('#demo2').load('request.php',{"displayMsg":msg},function(responseTxt, statusTxt, xhr){
        if(statusTxt == "success")
            console.log("External content loaded successfully!"+responseTxt);
        if(statusTxt == "error")
            console.log("Error: " + xhr.status + ": " + xhr.statusText);
    });
    }
     });
     </script>
     </html>
    

    this is my php file

      if( $_REQUEST["displayMsg"] ){
         $msg = $_REQUEST['displayMsg'];
         echo "".$msg ;
      }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • duanheyi7147 2018-06-29 05:09
    关注

    in JS

    var request = $.ajax({
            async: false,
            url: 'Php.file', / your php file path
            type: "POST",
            data: "Value1=your value";
            datatype: 'html',
        });
        request.done(function(data) {
            //data you will handle from php file
        });
    

    in PHP receive

    $data = $_POST['data'];
      //you can check like this
      if(empty($data))
      {
        echo("none received");
      }
      else{
       echo 'passed parameter '+$data;
       //in here you will receive as data in js file
    you will receive in data in js as 'passed parameter+ your value'
      }
    
    评论
  • dongzhao4036 2018-06-29 05:36
    关注

    First of all is to create an HTML file with jQuery included.

    Let's say you have a hidden input field.

    <input type="hidden" id="mydata" value="sampledata">

    You can now get the data from the hidden field using the script $("#mydata").val();

    You can now write the ajax code as follows

    $.ajax({ 
      type: 'post',
      url: '/path/to/ajax.php',
      data: {
        postvariable: $("#mydata").val()
      },
      success: function() {
        alert('success');
      }
    });
    

    In your ajax.php file, you can now receive the value as $_POST['postvariable']

    You can now declare $myphpvar = $_POST['postvariable'];

    Where echo $myphpvar; //will print 'sampledata' without quotes

    To summarize, it is simply like submitting a form with the having the method post. Except when using ajax it does not require the page to reload.

    You may read more about this in my tutorial: https://www.davidangulo.xyz/website-development/how-to-pass-value-from-javascript-to-php/

    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 webapi的部署(标签-服务器)
  • ¥20 怎么加快手机软件内部计时的时间(关键词-日期时间)
  • ¥15 C语言除0问题的检测方法
  • ¥15 为什么四分管的内径有的是16mm有的15mm,四分不应该是12.7mm吗
  • ¥15 macos13下 ios交叉编译的问题
  • ¥15 bgz压缩文件怎么打开
  • ¥15 封装dll(引入了pcl的点云设计库)
  • ¥30 关于#开发语言#的问题:我需要在抄板的基础上再抄板抄程序,根据RDA8851CM基础上开发
  • ¥15 oracle 多个括号,怎么删除指定的括号及里面的内容?
  • ¥15 小新14API2019想用bios调风扇