我有这样的功能:
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中显示正确的值。
答案 0 :(得分:1)
这一行是你的问题:
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);
});
答案 1 :(得分:0)
试试这个:
var record_no= '';
$.get(root+"/blocks/stickynotes/max_records.php", function(resp) {
alert(resp);
record_no+=resp;
})