Ошибка JavaScript после обновления до Drupal 7 - PullRequest
1 голос
/ 10 февраля 2012

Я опубликовал аналогичный вопрос на форуме Drupal, но мне не повезло.Я обновляю сайт с D6 до D7.Пока все прошло хорошо, но я получаю ошибку Javascript, для которой просто не могу найти решение.Это урезанная версия всего скрипта:

(function($) {
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) { 
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256); 
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}

function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}

Date.prototype.toISODate =
new Function("with (this)\nreturn " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");

function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));

Часть, которая продолжает выдавать ошибку, которую я вижу в Firebug, находится по адресу:

Date.prototype.toISODate =
new Function("with (this)\n    return " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");

Firebug продолжает останавливаться на "addZero не определен ".JS никогда не был моей сильной стороной, и я знаю, что в D7 были сделаны некоторые изменения.Я уже обернул весь скрипт в "(function ($) {} (jQuery));", но я должен пропустить что-то еще.Тот же скрипт отлично работает на сайте D6.

Вот «исправленная» версия всего кода с добавленным предложением @Pointy.Все, что я пропустил, - это часть скрипта для создания хэша, которая отправляется в Amazon, и некоторые из моих объявленных переменных.

<code>(function($) {
var typedText;
var strSearch = /asin:/;
var srchASIN;
   $(document).ready(function() {
      $("#edit-field-game-title-und-0-asin").change(function() {
         typedText = $("#edit-field-game-title-und-0-asin").val();
         $.ajax({
            type: 'POST',
            data: {typedText: typedText},
            dataType: 'text',
            url: '/asin/autocomplete/',
            success:function(){
               document.getElementById('asin-lookup').style.display='none';
               x = typedText.search(strSearch);
               y = (x+5);
               srchASIN = typedText.substr(y,10)
               amazonSearch();
            }
         });
      });  

      $("#search_asin").click(function() {
         $("#edit-field-game-title-und-0-asin").val('');
         document.getElementById('name-lookup').style.display='none';
         $("#edit-field-game-title-und-0-asin").val('');
         $("#edit-title").val('');
         $("#edit-field-subtitle-und-0-value").val('');
         $("#edit-field-game-edition-und-0-value").val('');
         $("#edit-field-release-date-und-0-value-date").val('');
         $("#edit-field-asin-und-0-asin").val('');
         $("#edit-field-ean-und-0-value").val('');
         $("#edit-field-amazon-results-und-0-value").val('');
         $("#edit-body").val('');
         srchASIN = $("#field-asin-enter").val();
         amazonSearch();
      });

      $("#clear_search").click(function() {
         $("#field-asin-enter").val(''); 
         $("#edit-field-game-title-und-0-asin").val('');
         $("#edit-title").val('');
         $("#edit-field-subtitle-und-0-value").val('');
         $("#edit-field-game-edition-und-0-value").val('');
         $("#edit-field-release-date-und-0-value-date").val('');
         $("#edit-field-release-dt2-und-0-value-date").val('');
         $("#edit-field-asin-und-0-asin").val('');
         $("#edit-field-ean-und-0-value").val('');
         $("#edit-field-amazon-results-und-0-value").val('');
         $("#field-amazon-platform").val('');
         $("#field-amazon-esrb").val('');
         $("#edit-body-und-0-value").val('');
         document.getElementById('asin-lookup').style.display='';
         document.getElementById('name-lookup').style.display='';
      });

      function amazonSearch(){
         var ASIN = srchASIN;
         var azScr = cel("script");
         azScr.setAttribute("type", "text/javascript");
         var requestUrl = invokeRequest(ASIN);
         azScr.setAttribute("src", requestUrl);
         document.getElementsByTagName("head").item(0).appendChild(azScr);
      }
   });

var amzJSONCallback = function(tmpData){
   if(tmpData.Item){
      var tmpItem = tmpData.Item;
   }
   $("#edit-title").val(tmpItem.title);
   $("#edit-field-game-edition-und-0-value").val(tmpItem.edition);
   $("#edit-field-release-date-und-0-value-date").val(tmpItem.relesdate);
   $("#edit-field-release-dt2-und-0-value-date").val(tmpItem.relesdate);
   $("#edit-field-asin-und-0-asin").val(tmpItem.asin);
   $("#edit-field-ean-und-0-value").val(tmpItem.ean);
   $("#field-amazon-platform").val(tmpItem.platform);
   $("#field-amazon-publisher").val(tmpItem.publisher);
   $("#field-amazon-esrb").val(tmpItem.esrb); 
};
function ctn(x){ return document.createTextNode(x); }
function cel(x){ return document.createElement(x); }
function addEvent(obj,type,fn){
   if (obj.addEventListener){obj.addEventListener(type,fn,false);}
   else if (obj.attachEvent){obj["e"+type+fn]=fn; obj.attachEvent("on"+type,function(){obj["e"+type+fn]();});}
}

var styleXSL = "http://www.tlthost.net/sites/vglAmazonAsin.xsl";
function invokeRequest(ASIN) {
  cleanASIN = ASIN.replace(/[-' ']/g,'');
  var unsignedUrl = "http://xml-us.amznxslt.com/onca/xml?Service=AWSECommerceService&AssociateTag=theliterarytimes&IdType=ASIN&ItemId="+cleanASIN+"&Operation=ItemLookup&ResponseGroup=Medium,ItemAttributes,OfferFull&Style="+styleXSL+"&ContentType=text/javascript&CallBack=amzJSONCallback";
    var lines = unsignedUrl.split("\n");
    unsignedUrl = "";
    for (var i in lines) { unsignedUrl += lines[i]; }
  // find host and query portions
  var urlregex = new RegExp("^http:\\/\\/(.*)\\/onca\\/xml\\?(.*)$");
  var matches = urlregex.exec(unsignedUrl);
  var host = matches[1].toLowerCase();
  var query = matches[2];
  // split the query into its constituent parts
  var pairs = query.split("&");
  // remove signature if already there
  // remove access key id if already present 
  //  and replace with the one user provided above
  // add timestamp if not already present
  pairs = cleanupRequest(pairs);
  // encode the name and value in each pair
  pairs = encodeNameValuePairs(pairs);
  // sort them and put them back together to get the canonical query string
  pairs.sort();
  var canonicalQuery = pairs.join("&");
  var stringToSign = "GET\n" + host + "\n/onca/xml\n" + canonicalQuery;
  // calculate the signature
  //var secret = getSecretAccessKey();
  var signature = sign(secret, stringToSign);
  // assemble the signed url
  var signedUrl = "http://" + host + "/onca/xml?" + canonicalQuery + "&Signature=" + signature;
  //document.write ("<html><body><pre>REQUEST: "+signedUrl+"
"); return signatureUrl;} функция encodeNameValuePairs (пары){for (var i = 0; i 16) {secretBytes = core_sha256 (secretBytes, secret.length * chrsz);} var ipad = Array (16), opad = Array (16);for (var i = 0; i <16; i ++) {ipad [i] = secretBytes [i] ^ 0x36363636;opad [i] = secretBytes [i] ^ 0x5C5C5C5C;} var imsg = ipad.concat (messageBytes);var ihash = core_sha256 (imsg, 512 + message.length * chrsz);var omsg = opad.concat (ihash);var ohash = core_sha256 (omsg, 512 + 256);var b64hash = binb2b64 (ohash);var urlhash = encodeURIComponent (b64hash);вернуть urlhash;} Date.prototype.toISODate = function () {function addZero (n) {return (n <0 || n> 9? "": "0") + n;} var d = this;return d.getFullYear () + '-' + addZero (d.getMonth () + 1) + '-' + addZero (d.getDate ()) + 'T' + addZero (d.getHours ()) + ':'+ addZero (d.getMinutes ()) +': '+ addZero (d.getSeconds ()) +' .000Z ';};function getNowTimeStamp () {var time = new Date ();var gmtTime = new Date (time.getTime () + (time.getTimezoneOffset () * 60000));return gmtTime.toISODate ();}} (jQuery));

1 Ответ

0 голосов
/ 10 февраля 2012

Вот лучшая версия вашего кода:

Date.prototype.toISODate = function() {
  function addZero(n) {
   return ( n < 0 || n > 9 ? "" : "0" ) + n;
  }
  var d = this;
  return d.getFullYear() + '-' + 
    addZero(d.getMonth() + 1) + '-' +
    addZero(d.getDate()) + 'T' +
    addZero(d.getHours()) + ':' +
    addZero(d.getMinutes()) + ':' +
    addZero(d.getSeconds()) + '.000Z';
};

Это перемещает «addDate» внутри функции расширения и позволяет избежать ужасного оператора with.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...