第一种情况:java ———– servlet
第一步:ajax代码
function commonQuery(){
$.ajax( { url:"http://www.abao.red/deep-qa-web/api/ask",
data:{ "n" : 1, "q" : _key //_key是输入的问题:西游记的作者是谁?},
type:'get',
dataType:'jsonp',
jsonp: "callbackparam",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback)
jsonpCallback:"success_jsonpCallback",
success:function(data) { //alert(data[0].answer);$('#slist').html(data[0].answer);}, error : function() { // view("异常!"); //alert("异常!"); } }); }第二步:servlet代码:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("application/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
String questionStr = request.getParameter("q");
String n = request.getParameter("n");
int topN = -1;
if(n != null && StringUtils.isNumeric(n)){
Question question = null;
List candidateAnswers = null;
if (questionStr != null && questionStr.trim().length() > 3) {
question = SharedQuestionAnsweringSystem.getInstance().answerQuestion(questionStr);
if (question != null) {
candidateAnswers = question.getAllCandidateAnswer(); } } try (
PrintWriter out = response.getWriter()) {
String json = JsonGenerator.generate(candidateAnswers, topN);
String jsonpCallback=request.getParameter("callbackparam");
out.println(jsonpCallback+"("+json+")"); } }
第二种情况:java ———– struts2
第一步:ajax代码
$(function(){//异步获取数据
$.ajax({ url: "http://127.0.0.1:8888/shanghaiuse/ceshi_queryPurchaseSubscribeList.action",
type:'get',
cache:false,
dataType:'jsonp',
jsonp: "callback",
jsonpCallback:"success_jsonpCallback",
success:function(data) {
var obj = data.subscribeDataList; //由JSON字符串转换为JSON对象alert(obj);},
error:function(XMLHttpRequest, textStatus, errorThrown){alert(textStatus+" 异常 "+errorThrown);}}); });第二步:配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="contact" extends="json-default">
<action name="ceshi_*" class="useController_ceshi" method="{1}">
<!-- 返回类型为json 在sjon-default中定义 -->
<result name="json" type="json">
<!-- root的值对应要返回的值的属性 -->
<!-- 这里的result值即是 对应action中的 result
<param name="root">result</param>
</result>
</action>
</package>
</struts>
-第三步:java代码...
Map<String,Object> jsonObject = new HashMap<String,Object>();
//jsonObject.put("total",total);
jsonObject.put("subscribeDataList",
subscribeDataList==null?(new ArrayList<ListingResourceSteel>()):subscribeDataList ); result="success_jsonpCallback("+JSONObject.fromObject(jsonObject).toString()+")";
PrintWriter out = response.getWriter();
response.setContentType("application/xml;charset=UTF-8");
out.write(result);
...
疑问:第一种情况将返回值放在response里可以理解,第二种可以将返回值配置在xml里么?