簡體   English   中英

帶有Ebay API的JS功能范圍

[英]JS Function Scope with Ebay API

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>

希望這可以幫助您了解縮進級別的范圍。 通常,縮進時可以使用它來幫助您可視化范圍級別。 可以在子級中訪問在父級范圍中聲明的變量,但不能以其他方式訪問。

<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>

未捕獲的ReferenceError:_cb_findItemsByKeywords未定義

您收到此錯誤是因為Javascript無法找到_cb_findItemsByKeywords函數。

問題是什么?

您正在創建一個腳本元素並將其添加到DOM中,該DOM具有_cb_findItemsByKeywords函數作為URL中的回調。

s = document.createElement('script'); //創建腳本元素s.src = url; document.body.appendChild(s); document.write(“” + url +“”);

現在,該腳本將在全局上下文中運行,並且在那里找不到任何_cb_findItemsByKeywords函數,因為您是在另一個函數內部定義了該腳本。

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

(請記住:每個函數都會創建自己的上下文)

解:

_cb_findItemsByKeywords函數添加到窗口對象。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM