【问题标题】:JS Function Scope with Ebay API带有 Ebay API 的 JS 函数范围
【发布时间】:2018-04-17 21:52:48
【问题描述】:

js 初学者在这里。 ebay 网站上有使用 javascript 发送 api 请求的示例代码。代码开箱即用,但是当我将整个代码包装在以下代码中时代码会中断:

(document).ready( function() { ('button').click( function() { //(ebays sample code here) }); });

谷歌浏览器控制台说我的错误是:

Uncaught ReferenceError: _cb_findItemsByKeywords is not defined
at http://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&SECURITY-APPNAME=micahelr-layitont-PRD-f51ca6568-6366e278&GLOBAL-ID=EBAY-US&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=accord&paginationInput.entriesPerPage=5&itemFilter(0).name=MaxPrice&itemFilter(0).value=30&itemFilter(0).paramName=USD&itemFilter(1).name=ListingType&itemFilter(1).value(0)=AuctionWithBIN&itemFilter(1).value(1)=FixedPrice:1:5
(anonymous) @ svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&SECURITY-APPNAME=micahelr-layitont-PRD-f51ca6568-6366e278&GLOBAL-ID=EBAY-US&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=accord&paginationInput.entriesPerPage=5&itemFilter(0).name=MaxPrice&itemFilter(0).value=30&itemFilter(0).paramName=USD&itemFilter(1).name=ListingType&itemFilter(1).value(0)=AuctionWithBIN&itemFilter(1).value(1)=FixedPrice:1

我想出的是,我的回调函数的范围不正确。我将.ready().click() 语句移动到脚本标签中的许多不同位置,试图在不完全了解如何解决的情况下解决问题。我尝试阅读有关函数范围的信息,但它似乎是我无法弄清楚的东西。以下是嵌入JS代码的mt HTML文件内容:

<html>
<head>
</head>
<body>
<button>click</button>   


<script>
$(document).ready(function() {
$('button').click( function() {


var urlfilter = "";
item_MaxPrice = Number(document.getElementById('pagePrice').innerHTML);    
inputKeywords = 'accord';


var filterarray = [ {"name":"MaxPrice", "value":item_MaxPrice, "paramName":"USD"}, ];


function _cb_findItemsByKeywords(root) {
    var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
    var html = [];
    html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3">

    for (var i = 0; i < items.length; ++i) {
        var item = items[i];
        html.push('text here');};
    document.getElementById("results").innerHTML = html.join("");};



// Generates an indexed URL snippet from the array of item filters
function  buildURLArray() {
    for(var i=0; i<filterarray.length; i++) {
        var itemfilter = filterarray[i];
        for(var index in itemfilter) {
            if (itemfilter[index] !== "") {
            if (itemfilter[index] instanceof Array) {
            for(var r=0; r<itemfilter[index].length; r++) {
                var value = itemfilter[index][r];
                urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value ;
      }
    }
    else {
      urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + 
itemfilter[index];
    }}}}}



// Execute the function to build the URL filter
buildURLArray(filterarray);    


var url = "http://svcs.ebay.com/services/search/FindingService/v1";
    url += "?OPERATION-NAME=findItemsByKeywords";
    url += "&SERVICE-VERSION=1.0.0";
    url += "&SECURITY-APPNAME=micahelr-layitont-PRD-f51ca6568-6366e278";
    url += "&GLOBAL-ID=EBAY-US";
    url += "&RESPONSE-DATA-FORMAT=JSON";
    url += "&callback=_cb_findItemsByKeywords";
    url += "&REST-PAYLOAD";
    url += "&keywords="+inputKeywords;
    url += "&paginationInput.entriesPerPage=5";
    url += urlfilter;


s=document.createElement('script'); // create script element
s.src= url;
document.body.appendChild(s);    
document.write("<a href='" + url + "'>" + url + "</a>");
})});
</script>

</body>
<footer>&copy;darnell cross 2018</footer>
</html>

【问题讨论】:

  • 请正确缩进您的代码。使关于范围的推理变得容易得多。
  • 如何正确缩进 javascript 代码?我使用括号作为我的编辑器,似乎很难做到一致的缩进,似乎它根本不重要。更不用说stackoverflow似乎也不一致地格式化我的代码。我来自 python 的背景。
  • 听起来你使用了错误的编辑器或配置错误,缩进对于可读性非常重要——就像在 Python 中一样。另一方面,StackOverflow 根本不会格式化您的代码。

标签: javascript scope callback ebay-api


【解决方案1】:

未捕获的 ReferenceError:_cb_findItemsByKeywords 未定义

您收到此错误是因为 Javascript 找不到 _cb_findItemsByKeywords 函数。

有什么问题?

您正在创建一个脚本元素并将其添加到具有 _cb_findItemsByKeywords 函数的 DOM 作为 URL 中的回调。

s=document.createElement('script'); // 创建脚本元素 s.src= 网址; document.body.appendChild(s); document.write("" + url + "");

现在,脚本将在全局上下文中运行,并且不会在那里找到任何 _cb_findItemsByKeywords 函数,因为您在另一个函数中定义了它。

$(document).ready(function() {...}

(记住:每个函数都创建自己的上下文)

解决办法:

_cb_findItemsByKeywords 函数添加到窗口对象。

window._cb_findItemsByKeywords = function() {...}

【讨论】:

    【解决方案2】:

    希望这可以帮助您了解缩进级别的范围。通常,当您缩进时,您会使用它来帮助您可视化范围级别。在父作用域中声明的变量可以在子作用域中访问,但反之则不行。

    <html>
    
    <head>
    </head>
    
    <body>
      <button>click</button>
    
    
      <script>
        $(document).ready(function() {
              $('button').click(function() {
    
                  //start of scope
                  var urlfilter = "";
                  item_MaxPrice = Number(document.getElementById('pagePrice').innerHTML);
                  inputKeywords = 'accord';
    
    
                  var filterarray = [{
                    "name": "MaxPrice",
                    "value": item_MaxPrice,
                    "paramName": "USD"
                  }, ];
    
    
                  function _cb_findItemsByKeywords(root) {                           
                    var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
                    var html = [];
                    html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3">
    
                      for (var i = 0; i < items.length; ++i) {
                         //start of new scope (can access everything in parent scope but nothing in a scope that is further nested    
                        var item = items[i];
                        html.push('text here');
                        //end of new scope
                      }; document.getElementById("results").innerHTML = html.join("");
                    };
    
    
    
                    // Generates an indexed URL snippet from the array of item filters
                    function buildURLArray() {
                      for (var i = 0; i < filterarray.length; i++) {
                        var itemfilter = filterarray[i];
                        for (var index in itemfilter) {
                          if (itemfilter[index] !== "") {
                            if (itemfilter[index] instanceof Array) {
                              for (var r = 0; r < itemfilter[index].length; r++) {
                                var value = itemfilter[index][r];
                                urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value;
                              }
                            } else {
                              urlfilter += "&itemFilter\(" + i + "\)." + index + "=" +
                                itemfilter[index];
                            }
                          }
                        }
                      }
                    }
    
    
    
                    // Execute the function to build the URL filter
                    buildURLArray(filterarray);
    
    
                    var url = "http://svcs.ebay.com/services/search/FindingService/v1";
                    url += "?OPERATION-NAME=findItemsByKeywords";
                    url += "&SERVICE-VERSION=1.0.0";
                    url += "&SECURITY-APPNAME=micahelr-layitont-PRD-f51ca6568-6366e278";
                    url += "&GLOBAL-ID=EBAY-US";
                    url += "&RESPONSE-DATA-FORMAT=JSON";
                    url += "&callback=_cb_findItemsByKeywords";
                    url += "&REST-PAYLOAD";
                    url += "&keywords=" + inputKeywords;
                    url += "&paginationInput.entriesPerPage=5";
                    url += urlfilter;
    
    
                    s = document.createElement('script'); // create script element
                    s.src = url;
                    document.body.appendChild(s);
                    document.write("<a href='" + url + "'>" + url + "</a>");
                  })
              //end of button scope
              });
      </script>
    
    </body>
    <footer>&copy;darnell cross 2018</footer>
    
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多