说出去都是泪啊~~~
找了大半天,都是含糊其辞的答案,一点也找不到精准一点的答案。。。
来,上代码:
客户端
main.js 配置
import VueResource from 'vue-resource'
...
Vue.use(VueResource)
//以下代码必须写在Vue.use(VueResource)后面
Vue.http.options.emulateHTTP = true;
Vue.http.options.emulateJSON = true;
Vue.http.headers.common['Content-Type'] = 'application/json'
Vue.http.headers.common['Access-Control-Allow-Origin'] = '*'
Vue.http.headers.common['Accept'] = 'application/json, text/plain, */*'
Vue.http.headers.common['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, Authorization, Access-Control-Allow-Origin'
Hello.vue
注意配置jsonpCallback很重要
...
<script>
export default{
...
methods:{
login(){
let data = {}
this.$http.jsonp(this.url,{
params:data,
jsonp: 'callBackParam',
jsonpCallback: "success_jsonpCallback"
}
).then((res)=>{
if(res.data){
console.log(res)
}
},(err)=>{
console.log(err)
});
}
}
}
</script>
...
服务器端
HelloAction.java
注意最后返回的数据格式是:"success_jsonpCallback(<json字符串>)"
...
public string hello(){
JSONObject result = new JSONObject();
result.put("status", "ok");
...
try {
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=utf-8");
Object o = "success_jsonpCallback("+result+")";
PrintWriter out=response.getWriter();
if(null!=o){
out.print(o.toString());
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
...
总结:填坑之路悠长悠长的,需保重身体啊~,T_T 千万别冲动啊~~
网友评论