描述你的问题
用原生javascript实现的jsonp方法,后端代码用的是php,在执行的时候,遇到了这样的问题,请问如何解决?
贴上相关代码
getJSONP : function(url,callback){
//为本次请求创建唯一的一个回调函数名称
var cbnum = "cb" + this.getJSONP.counter++; //
var cbname = "getJSONP."+cbnum; //作为JSONP函数的属性
if(url.indexOf("?") === -1){
url += "?jsonp="+cbname;
}else{
url += "&jsonp="+cbname;
}
//创建script元素用于发送请求
var script = document.createElement("script");
//定义将脚本执行的回调函数
this.getJSONP[cbnum] = function(response){
//response.ContentType("application/javascript");
try{
callback(response); //处理响应数据
}
finally{
delete getJSONP[cbnum]; //删除该函数
script.parentNode.removeChild(script); //移除script元素
}
};
//立即出发HTTP请求
script.src = url;
script.charset = "utf-8";
script.type = "text/javascript";
document.body.appendChild(script);
}
贴上报错信息
Refused to execute script from 'https://api.github.com/users/xxx?jsonp=getJSONP.cb0' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.
已经尝试过哪些方法仍然没解决(附上相关链接)
解决方法中提到通过设置contentType为application/javascript
就好,请问要如何设置呢?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
要在你的后端PHP代码中设置,在响应头部设置
Content-Type
为application/javascript
。header()