[英]Uncaught SyntaxError: Unexpected token ) when calling a function
I am wanting to write some code to return some data from an aJax call. 我想编写一些代码以从aJax调用返回一些数据。
Here is the resource that I am referring to: http://www.w3schools.com/jquery/ajax_ajax.asp 这是我指的资源: http : //www.w3schools.com/jquery/ajax_ajax.asp
Here is the code that I have written: 这是我编写的代码:
var data = getData("http://www.file.txt", function(result));
alert(data);
function getData(dataUrl, result)
{
$.ajax({url: dataUrl, success: function(result){
return result;
}});
}
I am getting the following error: 我收到以下错误:
Uncaught SyntaxError: Unexpected token )
未捕获到的SyntaxError:意外令牌)
At this line of code: 在这一行代码中:
var data = getData("http://www.file.txt", function(result));
Also, is the above code efficient when getting large amounts of data? 另外,上述代码在获取大量数据时是否有效?
Thanks 谢谢
This is not the correct syntax for a callback, plus the asynchronous call doesn't quite work like that. 这不是回调的正确语法,再加上异步调用不能完全正常工作。 Try this instead -
data
is set in the callback. 请改试试-
data
已在回调中设置。
var data;
getData("http://www.file.txt");
function getData(dataUrl)
{
$.ajax({url: dataUrl, success: function(result){
data = result;
alert(data);
}});
}
From JavaScript basics, a function should satisfy following. 从JavaScript基础来看,函数应满足以下条件。
So the line of code is actually incorrect. 因此,代码行实际上是不正确的。
var data = getData("http://www.file.txt", function(result));
It should be either of the below. 它应该是以下任意一个。
var data = getData("http://www.file.txt", function(result) {
//anonymous function body
});
or 要么
var data = getData("http://www.file.txt", callbackFn(result));
function callbackFn(result) {
//function body goes here.
}
You are not passing brackets so you get Uncaught SyntaxError: Unexpected token) error 您没有通过方括号,因此会出现Uncaught SyntaxError:Unexpected token)错误
var data = getData("http://www.file.txt", function(result){});
But I think you have to use function like this 但是我认为你必须使用这样的功能
function getData() { return Promise(function(resolve, reject) { $.ajax({ // ... success: function(data) { resolve(data); }, error: function(jqxhr, status, error) { reject(error); } }); }); } getData("http://www.file.txt").then(function(result) { console.log(result); }).catch(function() { // an error occurred });
If you are using ajax call, then you must use success
or .then
with it to be executed as callback after receiving data. 如果使用的是ajax调用,则必须使用
success
或.then
并将其与接收数据后作为回调执行。
The code should be only this: 该代码应该仅仅是这样:
var data = '';
$.ajax({url: dataUrl, success: function(result){
data = result;
alert(data);
}});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.