【问题标题】:Unexpected identifier in JSON Eval function [closed]JSON Eval函数中的意外标识符[关闭]
【发布时间】:2013-03-05 02:42:11
【问题描述】:

这是我在某处复制的用于对页面进行评分的代码。此代码在我的本地主机上运行良好,但当我将其上传到服务器时它返回语法错误。

 function rtgAjax(elm, ratev) {
   var cerere_http =  get_XmlHttp();        // get XMLHttpRequest object

 // define data to be send via POST to PHP (Array with name=value pairs)
  var datasend = Array();
  for(var i=0; i<elm.length; i++) datasend[i] = 'elm[]='+elm[i];
     // joins the array items into a string, separated by '&'
     datasend = datasend.join('&')+'&rate='+ratev;

     cerere_http.open("POST", 'ratingfiles/ratings.php', true);         
       //     crate the request

  cerere_http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");              // header for POST
  cerere_http.send(datasend);       
 //  make the ajax request, poassing the data

 // checks and receives the response
 cerere_http.onreadystatechange = function() {
if (cerere_http.readyState == 4) {
  // receives a JSON with one or more item:['totalrate', 'nrrates', renot]
  eval(' var jsonitems = ' + cerere_http.responseText);

  // if jsonitems is defined variable
  if (jsonitems) {
    // parse the jsonitems object
    for(var rtgitem in jsonitems) {
      var renot = jsonitems[rtgitem][2];        
  // determine if the user can rate or not

      // if renot=3 displaies alert that already voted, else, continue with the rating reactualization
       if(renot == 3) {
        alert("You already voted \n You can rate again tomorrow");
        window.location.reload(true);       // Reload the page
      }
      else addRtgData(rtgitem, jsonitems[rtgitem][0], jsonitems[rtgitem][1], renot);    // calls function that shows rating
    }
  }

这一行,

 eval(' var jsonitems = ' + cerere_http.responseText);

返回一个语法错误:Unexpected Identifier

【问题讨论】:

  • 你应该显示cerere_http.responseText中的值
  • responseText 不能是有效的 JSON。此外,您可能知道,eval() 非常危险。

标签: javascript json syntax eval


【解决方案1】:

eval 不应以这种方式使用。相反,试试这个:

var jsonitems;
try {
    jsonitems = JSON.parse(cerere_http.responseText);
}
catch(e) {alert("Failed to parse JSON: "+e);}

【讨论】:

  • 返回意外的令牌 U
  • 表示你的 JSON 无效。尝试输出它,看看你得到了什么。
  • 注意:如果必须支持IE7,则不支持JSON.parse。所以你可能想研究一个 polyfill,比如 Crockford 的json2。正如@Kolink 所说,很明显您的响应无论如何都不是有效的 JSON,所以这是您的第一个也是主要的问题。
猜你喜欢
  • 2018-03-09
  • 1970-01-01
  • 2013-10-14
  • 2020-11-10
  • 2012-09-23
  • 2014-12-02
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
相关资源
最近更新 更多