How do I give JavaScript variables data from ASP.NET variables?

后端 未结 9 1070
野趣味
野趣味 2020-11-28 08:46

I have created a SCORM API for our LMS and right now I am using hard coded userID and courseID variables (variables that reference things in the database). I need to pass th

9条回答
  •  温柔的废话
    2020-11-28 09:16

    All the answers here that suggest something like

    var userID = '<%= UserID %>';
    

    are all missing something important if the variable you are embedded can contain arbitrary string data. The embedded string data needs to be escaped so that if it contains backslashes, quotes or unprintable characters they don't cause your Javascript to error.

    Rick Strahl has some suggestions for the escaping code needed here. Using Rick's code the embedded variable will look like this:

    var userId = <%= EncodeJsString(UserID) %>;
    

    Note that there are no quotes now, Rick's code wraps the escaped string with quotes.

提交回复
热议问题