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条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题