来自另一个函数的jQuery回调
我有一个类似这样的函数。它起作用了 问题 此函数来自另一个函数的jQuery回调,jquery,function,post,callback,Jquery,Function,Post,Callback,我有一个类似这样的函数。它起作用了 问题 此函数myFunction由许多其他函数调用,取决于它在成功时应执行的操作 问题 这是如何解决的?某种形式的回调?或者我必须发送一个额外的参数让函数知道吗 代码 function myfunction() { var value = "myvalue"; var post_url = "ajax.php"; $.post( post_url, { value: val
myFunction
由许多其他函数调用,取决于它在成功时应执行的操作
问题
这是如何解决的?某种形式的回调?或者我必须发送一个额外的参数让函数知道吗
代码
function myfunction()
{
var value = "myvalue";
var post_url = "ajax.php";
$.post(
post_url,
{
value: value,
},
function(responseText){
var json = JSON.parse(responseText);
if(json.success)
{
console.log('success');
}
}
);
}
}
让
myfunction
接受回调:
function myfunction(callback)
{
var value = "myvalue";
var post_url = "ajax.php";
$.post(post_url, { value: value }, callback);
}
然后,当POST
返回时,您可以传入任何要执行的函数:
myfunction(function(responseText){
var json = JSON.parse(responseText);
if (json.success)
{
console.log('success');
}
});
让
myfunction
接受回调:
function myfunction(callback)
{
var value = "myvalue";
var post_url = "ajax.php";
$.post(post_url, { value: value }, callback);
}
然后,当POST
返回时,您可以传入任何要执行的函数:
myfunction(function(responseText){
var json = JSON.parse(responseText);
if (json.success)
{
console.log('success');
}
});
添加函数参数并在成功时调用它:
function myfunction(callback)
{
var value = "myvalue";
var post_url = "ajax.php";
$.post(
post_url,
{
value: value,
},
function(responseText){
var json = JSON.parse(responseText);
if(json.success)
{
console.log('success');
//call callback
callback();
}
}
);
}
}
添加函数参数并在成功时调用它:
function myfunction(callback)
{
var value = "myvalue";
var post_url = "ajax.php";
$.post(
post_url,
{
value: value,
},
function(responseText){
var json = JSON.parse(responseText);
if(json.success)
{
console.log('success');
//call callback
callback();
}
}
);
}
}
是的,您需要有一个参数来标识调用方,如
function myfunction(caller) {
if (caller == "Foo") {
// some code
}
}
myFunction("Foo");
或者使用全局变量
function myFunction() {
if (caller == "Foo") {
// some code
}
}
caller = "Foo";
myFunction();
是的,您需要有一个参数来标识调用方,如
function myfunction(caller) {
if (caller == "Foo") {
// some code
}
}
myFunction("Foo");
或者使用全局变量
function myFunction() {
if (caller == "Foo") {
// some code
}
}
caller = "Foo";
myFunction();