dongzhi7763 2016-08-11 13:05
浏览 69
已采纳

将div的jquery值分配给php变量

I am using a jquery calendar script that assigns the content of a div using ajax.

$('#details-event-id').html(id);

The div tag:

<div id="details-event-id"></div>

is in another file and displays the id correctly.

<div id="details-event-id">91</div>

Is it possible to get the id, 91, to be assigned to a PHP variable?

  • 写回答

2条回答 默认 最新

  • doucheng3407 2016-08-11 14:12
    关注

    If I understand correctly you would like to send the variable id to a PHP file. You can achieve this by using AJAX. Bellow I'm showing two ways to get it done.

    var id = $('#details-event-id').html(id);
    

    AJAX with good old JS

    ajax(myfile.php, {id:id}, function() {
      // the following will be executed when the request has been completed
      alert('Variable id has been sent successfully!');
    });
    
    function ajax(file, params, callback) {
    
      var url = file + '?';
    
      // loop through object and assemble the url
      var notFirst = false;
      for (var key in params) {
        if (params.hasOwnProperty(key)) {
          url += (notFirst ? '&' : '') + key + "=" + params[key];
        }
        notFirst = true;
      }
    
      // create a AJAX call with url as parameter
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          callback(xmlhttp.responseText);
        }
      };
      xmlhttp.open('GET', url, true);
      xmlhttp.send();
    }
    

    AJAX with JQuery

    $.ajax({
      url: 'ajax.php', //This is the current doc
      type: "GET",
      data: ({
        id: id
      }),
      success: function(data) {
        // the following will be executed when the request has been completed
        alert('Variable id has been sent successfully!');
      }
    });
    

    Offtopic: you can see why some prefer JQuery...

    When either function (Jquery or plain JS) is launched it will send the variable id to the file myfile.php. In order to retrieve the variable from the call you won't use $_GET[...] but $_REQUEST[...].

    myfile.php

    <?php
    
    if(!isset($_REQUEST['id'])) {
      echo "no variable was sent";
    }
    
    $id = $_REQUEST['id'];
    // process data, save in db, etc ....
    

    You may return a value to the JS callback function by using echo() not return

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?