How to pass an object as function's parameter without getting Unexpected identifier error?

你说的曾经没有我的故事 提交于 2021-02-19 08:21:43

问题


I tried to passed the object as parameter in function getReqDetail but it returned Uncaught SyntaxError: Unexpected identifier. But when i passed a simple value(integer,boolean,string) as parameter such as data[i].id, it worked. So how do i passed the object as parameter

the data/object is from ajax function jquery

function agetAllRequests(){
    $.ajax({
        type: 'GET',
        url: `http://localhost:8080/api/requests`,
        headers: {
            "Content-Type": "application/json", "Accept": "application/json"
        },
        dataType:"json",
        success: function (data) {
            console.log("yes. data: " + data);
            if (data) {
                if (len > 0) {
                    for (var i = 0; i < len; i++) {
                        if(data[i]) {                            
                            console.log(data[i]);  
                            txt += `
                                    <tr class="hov" onclick="getReqDetails(${data[i]})">
                                           <td>${data[i].id}</td> 
                                           <td>${data[i].status}</td> 
                                           <td>${data[i].user.email}</td> 
                                           <td>${data[i].message}</td> 
                                           <td>${new Date(data[i].createdAt).toLocaleString()}</td>
                                    </tr>`;
                        }
                    }
                    if(txt){
                        $("#requestList").html(txt);
                    }
                }
            }
        },
        error: function (error) {
            console.log('errorCode: ' + error.status + ' . Message: ' + error.responseText);
        }
    });
}
function getReqDetails(data){
    console.log(data);
    return data;
}

EDIT : note: function getReqDetails is outside of ajax function

the error


回答1:


The reason for the error is that `onclick="getReqDetails(${data[i]})` will resolve to a string. Because data[i] is not a string it is converted to one, ie. "[object Object]". This makes the onclick attribute look like this:

onclick="getReqDetails([object Object])"

But that code is not valid JavaScript, hence the error.

In order to pass the object to the function, you should really not use the onclick attribute, which must have a string value. Instead bind a click handler, as follows:

    success: function (data) {
        console.log("yes. data: " + data);
        if (!data || !data.length) return;
        $("#requestList").empty(); // Clear whatever content there was before
        for (var i = 0; i < len; i++) {
            var item = data[i]; // Use a local variable to avoid repetition
            if(!item) continue;                            
            console.log(item);
            // Use jQuery methods to add the content and bind a click handler
            $("#requestList").append(
                $("<tr>").addClass("hov").append(
                    $("<td>").text(item.id),
                    $("<td>").text(item.status),
                    $("<td>").text(item.user.email),
                    $("<td>").text(item.message.id),
                    $("<td>").text(new Date(item.createdAt).toLocaleString())
                ).click(getReqDetails.bind(null, item)); // <-- click handler for TR
            );
        }
    },



回答2:


Template literals allows population of variables ( ${myVar} ) at runtime but the result will be always a string so the evaluation of your template will result in getReqDetails([object Object]).

What you can do is render a serializable value from your object or store a reference to the index then process it in the called function getReqDetails().

Try to pass a simple value to your string function:

var data = [{id: 1},{id: 2}, {id: 3},];
if (data) {
    var len = data.length;
    var txt = ``;
       if (len > 0) {
         for (var i = 0; i < len; i++) {
            if(data[i]) {                           
            txt += `
            <tr class="hov" onclick="getReqDetails(${data[i].id})">
                  <td>...<td>
            </tr>`;}
}
if(txt){
           $("#requestList").html(txt);
}
}
function getReqDetails(reqId){
     console.log(reqId)
     return reqId;
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="requestList" />



回答3:


I think it's problematic in the first place that the getReqDetails function is inside the success item in the AJAX statement. Since it's an onclick function, I think it should be globally defined.

Answering your main question, the Uncaught SyntaxError: Unexpected identifier is usually called when you have issues with your code syntactically. You may have extra/missing brackets, double parentheses, et cetera.

Looking at the second if statement in your code, you have some issues with your brackets. It should look like this:

  if (len > 0)
     for (var i = 0; i < len; i++) {
        if(data[i]) {                           
            console.log(data[i]);
            txt += `
            <!--<tr class="hov" onclick="getReqDetails(${data[i].id})">-->
            <tr class="hov" onclick="getReqDetails(${data[i]})">
                <td>...<td>
            </tr>`;
         }
     }

Here are the changes I made:

  • I remove the { in your if (len > 0) { since you have only one statement inside it, which is the for statement.
  • I add another closing bracket (}) for the for statement.

I hope this will fix your problem. I suggest you use a powerful code editor like Visual Studio Code or Atom for syntax highlighting, error checking, debugging, and so much more. If you prefer working on a terminal, I suggest using Vim.

Additionally, I strongly suggest you define the getReqDetails function outside the AJAX statement. I think, the reason your code works using an integer as an input, is because numbers on Javascript (if I'm not mistaken) doesn't have a length property -- Which leads your script not calling any error, because the value of len is null.

EDIT

Since you want the object to be a parameter on the onclick function, you need to convert it first to a string. You can do it by replacing ${data[i]} to ${JSON.stringify(data[i])}. Then on the getReqDetails function, you use the JSON.parse() function to read the param as an object.

Updated txt variable

txt += <tr class="hov" onclick="getReqDetails(${JSON.stringify(data[i])})"> <td>...<td> </tr>;

Updated getReqDetails function:

function getReqDetails(stringifiedObject){
    var data = JSON.parse(stringifiedObject)

    console.log(data);
    return data;
}


来源:https://stackoverflow.com/questions/53942509/how-to-pass-an-object-as-functions-parameter-without-getting-unexpected-identif

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!