简体   繁体   English

带有Ebay API的JS功能范围

[英]JS Function Scope with Ebay API

js beginner here. js初学者在这里。 the ebay website has sample code for sending an api request with javascript. ebay网站上有示例代码,用于使用javascript发送api请求。 the code works out of the box, but the code breaks when i wrap the entire code inside of: 该代码开箱即用,但是当我将整个代码包装在以下代码中时,代码将中断:

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

google chromes console says my error is: 谷歌浏览器控制台说我的错误是:

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

what i have come up with, is that the scope of my callback function is incorrect. 我想出的是,我的回调函数的范围不正确。 ive moved the .ready() and .click() statements in many different places within the script tags, trying to solve the problem without completely understanding how it can be fixed. 我将.ready().click()语句移到了脚本标记内的许多不同位置,试图解决该问题而不完全了解如何解决。 i tried reading about function scope but it seems like its something that i just cant figure out. 我尝试阅读有关函数范围的内容,但似乎我无法弄清楚。 the following is the content of mt HTML file with embedded JS code: 以下是带有嵌入式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>

Hopefully this helps you understand scope with indentation levels. 希望这可以帮助您了解缩进级别的范围。 Normally when you indent you use it to help you visualize the levels of scope. 通常,缩进时可以使用它来帮助您可视化范围级别。 A variable declared in a parent scope can be accessed in the child but not the other way around. 可以在子级中访问在父级范围中声明的变量,但不能以其他方式访问。

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

Uncaught ReferenceError: _cb_findItemsByKeywords is not defined 未捕获的ReferenceError:_cb_findItemsByKeywords未定义

You are getting this error because Javascript can't find the _cb_findItemsByKeywords function. 您收到此错误是因为Javascript无法找到_cb_findItemsByKeywords函数。

What is the problem? 问题是什么?

You are creating a script element and adding it to the DOM which is having _cb_findItemsByKeywords function as a callback in the URL. 您正在创建一个脚本元素并将其添加到DOM中,该DOM具有_cb_findItemsByKeywords函数作为URL中的回调。

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

Now, the script would run in the global context and wouldn't find any _cb_findItemsByKeywords function there because you defined it inside of another function. 现在,该脚本将在全局上下文中运行,并且在那里找不到任何_cb_findItemsByKeywords函数,因为您是在另一个函数内部定义了该脚本。

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

(Remember: Every function creates it's own context) (请记住:每个函数都会创建自己的上下文)

Solution: 解:

Add the _cb_findItemsByKeywords function to the window object. _cb_findItemsByKeywords函数添加到窗口对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM