如何使用$.get()将php变量值保存为javascript变量

How to save a php variable value to javascript variable using $.get()?

本文关键字:保存 变量值 javascript 变量 php 何使用 get      更新时间:2023-09-26

我有一个这样的函数:

jQuery.fn.stickyNotes.createNote = function(root) {
   var record_no;
   $.get(root+"/blocks/stickynotes/max_records.php", function(resp) {
      alert(resp);
      record_no=resp;
   })
   var note_stickyid = record_no;
   ...
}

max_record.php看起来像这样:

 <?php
     require_once('../../config.php');
     global $DB;
     $max_id = $DB->get_record_sql('
                  SELECT max(stickyid) as max_id   
                  FROM mdl_block_stickynotes
               ');
     $stickyid= $max_id->max_id+1;
     echo $stickyid;
 ?>

我想知道为什么records_no中没有值,而resp在alert中显示正确的值。

这一行是您的问题:

var note_stickyid = record_no;

它上面的$.get()函数是异步的,所以它试图在函数完成之前分配这个值。在回调中分配变量:

var note_stickyid;
$.get(root+"/blocks/stickynotes/max_records.php", function(resp) {
  alert(resp);
  record_no=resp;
  note_stickyid = record_no;
}).done(function() {
  alert(note_stickyid); //Works because it waits until the request is done
});
alert(note_stickyid); //This will alert null, because it triggers before the function has assigned!

在您的情况下,您可能希望传入一个回调函数,以便实际使用此变量,下面是一个示例回调函数:

function callback(param) {
    alert(param);
}

现在为您的createNote:设置另一个参数

jQuery.fn.stickyNotes.createNote = function(root, callback) {

现在在$.get:中使用该回调

var note_stickyid;
$.get(root+"/blocks/stickynotes/max_records.php", function(resp) {
  alert(resp);
  record_no=resp;
  note_stickyid = record_no;
  callback(note_stickyid);
});

试试这个:

var record_no= '';
   $.get(root+"/blocks/stickynotes/max_records.php", function(resp) {
      alert(resp);
      record_no+=resp;
   })