JSONP/Ajax 脚本的问题 - 返回“未定义”

Posted

技术标签:

【中文标题】JSONP/Ajax 脚本的问题 - 返回“未定义”【英文标题】:Problems with JSONP/Ajax Script - returning 'Undefined' 【发布时间】:2020-06-28 15:23:17 【问题描述】:

我正在尝试从我无法控制的网络服务器中检索数据。 我试过谷歌,但似乎没有任何解决办法。我尝试了一些不同的代码,包括有和没有 DataTables。

如果有人能指出我正确的方向,我将不胜感激。

 <script>
$(document).ready(function() 
$('#example').DataTable( 
    "ajax": 
        "url": 'https://Example.com',
        "dataSrc": "",
        "dataType": "jsonp"
    ,
    "columns": [
         "data": "name" ,
         "data": "description" 
    ]
 );
 );
</script>

当我在 chrome 中的网页上运行代码时,在开发人员工具/网络中我得到的 url 请求的结果

["ID":10,"VIRTUAL":"No","QTY":2,"NAME":"Alto TS Sub 15\"","ALT_NAME":"Alto TS15","DESCRIPTION":"","MEMO":"","PRICEA":0,"PRICEB":0,"PRICEC":0,"PRICE_TYPE":"per Day","TAX_RATE":"0%","STATUS":"Active","CATEGORY":"Speakers","CATEGORY_ID":9,"CATEGORY_LFT":18,"CATEGORY_RGT":19,"IMAGE_ID":101,"IMAGE_URL":"https:\/\/www.hirehop.info\/uploads\/Alto-TS-Sub-15in\/1758_101.png","REPLACE_COST":300,"WEIGHT":"31 kg","WIDTH":0.451,"LENGTH":0.513,"HEIGHT":0.591,"SERVICE_INTERVAL":"P6M","PAT_INTERVAL":"P1Y","TEST_INTERVAL":"P6M","LOCATION":"Greenway Avenue","PART_NUMBER":"","BARCODE":"","LAST_UPDATE":"2019-09-30 21:42:15","MARKETING":1,"NOMINAL_CODE":"","LINKS":[],"CUSTOM_FIELDS":[],"ID":9,"VIRTUAL":"No","QTY":2,"NAME":"Electro-Voice ZLX-12P","ALT_NAME":"EV-ZLX12P","DESCRIPTION":"12\" Active PA Speaker","MEMO":"","PRICEA":0,"PRICEB":0,"PRICEC":0,"PRICE_TYPE":"per Day","TAX_RATE":"0%","STATUS":"Active","CATEGORY":"Speakers","CATEGORY_ID":9,"CATEGORY_LFT":18,"CATEGORY_RGT":19,"IMAGE_ID":100,"IMAGE_URL":"https:\/\/www.hirehop.info\/uploads\/Electro-Voice-ZLX-12P\/1758_100.png","REPLACE_COST":350,"WEIGHT":"15.6 kg","WIDTH":0.35,"LENGTH":0.35,"HEIGHT":0.65,"SERVICE_INTERVAL":"P6M","PAT_INTERVAL":"P1Y","TEST_INTERVAL":"P3M","LOCATION":"Greenway Avenue","PART_NUMBER":"","BARCODE":"3","LAST_UPDATE":"2019-09-30 21:27:27","MARKETING":1,"NOMINAL_CODE":"","LINKS":[],"CUSTOM_FIELDS":[]]

【问题讨论】:

oreilly.com/library/view/javascript-the-definitive/0596000480/… 【参考方案1】:

你说:

"dataType": "jsonp"

...但 URL 返回 JSON,而不是 JSONP。

您必须使用与您获取的数据类型相匹配的数据类型(或完全忽略它并相信响应中的 Content-Type 标头是正确的)。

【讨论】:

没有“dataType”:“jsonp”,我在控制台日志中得到了这个。从源“bsgproductions.co.uk”访问“myhirehop.com/modules/stock/…”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。 @elliott37 — 这很正常,除非 bsgproductions 授予您权限。见***.com/a/35553666/19068

以上是关于JSONP/Ajax 脚本的问题 - 返回“未定义”的主要内容,如果未能解决你的问题,请参考以下文章

使用 jQuery 中止 JSONP ajax 请求

从 Javascript 调用 JSONP Ajax 回调

可编写脚本的插件,Javascript 返回未定义

从 url 获取参数返回“参数未定义”

mui.ajax 跨域怎么解决的

jsonp ajax 请求中的错误字符集