2015-04-06 122 views
1

我正在學習有關調用ajax的知識,所以我試圖獲得('#abcd')(html選擇)的值。我用這條線:

abcdVal = combo.options [combo.selectedIndex] .value的

當這個值改變,我必須像abcdVal一個VAR存儲他的價值傳配合與Servlet :

var data = {「text」:abcdVal};

j("#mybutton").click(function(){  
    j.ajax({method: 'POST', 
     url: "/bin/company/repo", 
     dataType: 'JSON', 
     data: data, 
     success:function(result){ 
      alert(result); 
      j("#demo").html(''); 
      j('#demo').html(result); 
     }}); 
}); 

我得到的價值,並把響應的文字平淡,但在HTML頁面中,我看到:

[{ 「文」:空, 「值」:10}]

相反[{ 「文本」 :(HTML的選擇值來選擇), 「值」:10}]的

做錯事然後我將數據傳遞到的servlet。我該如何正確傳遞這個變量?


我的代碼

Javascript代碼

<script type="text/javascript"> 
var j = jQuery.noConflict(); 
var abcdVal; 
j(document).ready(function(){ 
    //get a reference to the select element 
    //request the JSON data and parse into the select element 
    j.ajax({ 
     url: '/bin/company/repo', 
     dataType:'JSON', 
     success:function(data){ 
     //clear the current content of the select 
     j('#abcd').html(''); 
     //iterate over the data and append a select option 
     jQuery.each(data, function(text, value){ 
      j('#abcd').append('<option id="' + value.value + '">' +   value.text + '</option>'); 
     }); 
     }, 
     error:function(){ 
     //if there is an error append a 'none available' option 
     j('#abcd').html('<option id="-1">none available</option>'); 
     } 
}); 
j("#abcd").change(function(){ 
    var combo = document.getElementById('abcd'); 
    if(combo.selectedIndex<0) 
     alert('No hay opcion seleccionada'); 
    else 
     abcdVal = combo.options[combo.selectedIndex].value; 
     alert('La opcion seleccionada es: '+combo.options[combo.selectedIndex].value); 
}); 
var data = {"text" : abcdVal}; 
alert(data); 
j("#mybutton").click(function(){  
    j.ajax({method: 'POST', 
     url: "/bin/company/repo", 
     dataType: 'JSON', 
     data: data, 
     success:function(result){ 
      alert(result); 
      j("#demo").html(''); 
      j('#demo').html(result); 
     }}); 
}); 
}) 
</script> 

servlet代碼

@Override 
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, 
     IOException { 
     String text = (String) request.getParameter("text"); 
     response.setHeader("Content-Type", "text/html; charset=UTF-8"); 
     StringWriter writer = new StringWriter(); 
     TidyJSONWriter json = new TidyJSONWriter(writer); 
     try 
     { 
      json.array(); 
      //loop through your options and create objects as shown below 
      json.object(); 
      json.key("text"); 
      json.value(text); 
      json.key("value"); 
      json.value(10); 
      json.endObject(); 
      //end your array 
      json.endArray();  
     } catch(JSONException e) { 
      e.printStackTrace(); 
     } 

     response.getWriter().write(writer.toString());  // Write response body. 
} 

回答

1

我這樣做會更改解決我的問題:按類型POST: 'POST'

1)在Ajax調用變化的方法。

2)在調用ajax之前添加even.preventDefault()以便不使用默認提交。

3)更改我處理數據請求的表單。如果我不傳遞一個表單,我需要做這個檢索請求參數,如@Sabya解釋。

4)在成功(ajax)內部處理json以顯示html選擇選項。

因此,代碼是下一個:

的JavaScript

<script type="text/javascript"> 
var j = jQuery.noConflict(); 
var abcd = document.getElementById("abcd"); 
var selection = abcd.options[abcd.selectedIndex].value 
j(document).ready(function(){ 
    j.ajax({ 
      url: '/bin/company/repo', 
      dataType:'JSON', 
      success:function(data){ 
      jQuery.each(data, function(text, value){ 
      j('#abcd').append('<option id="' + value.value + '">' + value.text + '</option>'); 
     }); 
     }, 
     error:function(){ 
     //if there is an error append a 'none available' option 
     j('#abcd').html('<option id="-1">none available</option>'); 
     } 
    }); 
    j("#abcd").live('change',function(){ 
     var combo = document.getElementById('abcd'); 
     if(combo.selectedIndex<0) 
     alert('no option selected'); 
     else 
     selection = combo.options[combo.selectedIndex].value; 
    }); 

    j('form').on('submit', function(e){ 
     event.preventDefault(); 
     j.ajax({type: 'POST', 
     contentType: "application/json; charset=utf-8", 
     url: "/bin/company/repo", 
     dataType: 'JSON', 
     data: JSON.stringify({ "text": selection }), 
     success:function(data){ 
      jQuery.each(data, function(text, value){ 
       j('#demo').html(''); 
       j('#demo').html(value.text); 
      }); 
     }}); 
    }); 
}) 
</script> 

的Servlet

@Override 
protected void doPost(SlingHttpServletRequest request,  SlingHttpServletResponse response) throws ServletException, 
     IOException { 
     response.setHeader("Content-Type", "application/json"); 
     PrintWriter out = response.getWriter(); 
     StringWriter writer = new StringWriter(); 
     TidyJSONWriter json = new TidyJSONWriter(writer); 
     StringBuilder buffer = new StringBuilder(); 
     BufferedReader reader = request.getReader(); 
     String line; 
     while ((line = reader.readLine()) != null) { 
      buffer.append(line); 
     } 
     String data = buffer.toString(); 
     try 
     { 
      JSONObject jsonObj = new JSONObject(new String(data)); 
      json.array(); 
      //loop through your options and create objects as shown below 
      json.object(); 
      json.key("text"); 
      json.value(jsonObj.get("text")); 
      json.endObject(); 
      //end your array 
      json.endArray(); 
     } catch(JSONException e) { 
      e.printStackTrace(); 
     } 
     out.write(writer.toString()); 

} 
+0

也許代碼可以更乾淨,但這是一個解決方案 - @Sabya – jmhdez 2015-04-08 10:26:26

0

使用.live()代替.change(),因爲你選擇要素是動態的。

j("#abcd").live('change', function(){ 
    var combo = document.getElementById('abcd'); 
    if(combo.selectedIndex<0) 
     alert('No hay opcion seleccionada'); 
    else 
     abcdVal = combo.options[combo.selectedIndex].value; 
     alert('La opcion seleccionada es: '+combo.options[combo.selectedIndex].value); 
}); 
+0

我做到了,謝謝。你知道如何解決這個問題嗎?我想現在我必須使用一個BufferedReader或者其他的東西來讀取servlet中的數據。 - @Brijesh Bhatt – jmhdez 2015-04-06 11:17:57

+0

@jmhdez是servlet接收到的文本參數? – 2015-04-06 11:43:15

+0

當我做了request.getParameter(「text」); - @Brijesh Bhatt – jmhdez 2015-04-06 11:50:06

0

您可以檢查chrome的網絡面板中的servlet調用並檢查Request-Header和/或表單數據嗎?

不確定你在javascript中的問題,但是如果你在你的servlet中獲得NPE,那可能是因爲你沒有將它作爲表單數據發佈並試圖從請求參數中檢索它。

訪問作爲請求有效載荷發送的數據與訪問表單數據有點不同。

以下代碼片段可能會對您有所幫助,以防萬一您發現您將JSON發佈到servlet的請求負載爲

 BufferedReader reader = req.getReader(); 
     while ((line = reader.readLine()) != null) { 
      buffer.append(line); 
     } 

     String requestData = buffer.toString(); 

     //TODO: Retrieve required fields from this requestData string .