2014-12-08 91 views
0

我是JavaScript新手,希望獲得一些幫助。我正在嘗試基於文本框輸入發出JSON請求。我希望文本框是請求的一部分,但是我不能讓文本成爲一個字符串,以便它可以用於JSON請求。我究竟做錯了什麼?將文本框輸入轉換爲字符串

這裏是我的代碼:代碼

<html> 
<head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
</head> 
<body> 


<p id="syno"></p> 


<form name="test"> 
<input type="text" name="Edit"> <!-- where i input a word--> 
<input type="button" value="Test" onClick="gettext()"><!-- test button--> 
<input type="text" name="Edit2" value="power" readonly style="border:1px solid white"> 
</form> 


<script> 
function gettext() { 
document.test.Edit2.value = document.test.Edit.value; 
document.test.Edit2("Edit2").value = document.test.Edit.value; 
} 


var apiKey = '0771a4c95ca7e23d41e33f67a1da0000/'; 
var txtjson = '/json'; 
var f = document.test.Edit2.value; 
var apiUrl = 'http://words.bighugelabs.com/api/2/' + apiKey + f + txtjson; 

$.ajax({ 
     url: apiUrl, 
     type: "GET", 
     dataType: 'json', 
     success: parseWord 
    }); 

function parseWord(data) { 
      $('#syno').text(data.noun.syn); 
     } 

</script> 
</body> 
</html> 

回答

1

問題

  1. 您已經添加ajax代碼,但是代碼爲gettext()功能
  2. 代碼行之外document.test.Edit2("Edit2")應儘可能document.forms.test.Edit2.value

看到cor RECT代碼,

function gettext() { 
 

 
    document.forms.test.Edit2.value = document.forms.test.Edit.value; 
 
    var apiKey = '0771a4c95ca7e23d41e33f67a1da0000/'; 
 
    var txtjson = '/json'; 
 
    var f = document.forms.test.Edit2.value; 
 
    var apiUrl = 'http://words.bighugelabs.com/api/2/' + apiKey + f + txtjson; 
 

 
    $.ajax({ 
 
    url: apiUrl, 
 
    type: "GET", 
 
    dataType: 'json', 
 
    success: parseWord 
 
    }); 
 
    return false; 
 
} 
 

 

 

 

 
function parseWord(data) { 
 
    $('#syno').text(data.noun.syn); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p id="syno"></p> 
 
<form name="test"> 
 
    <input type="text" name="Edit" /> 
 
    <!-- where i input a word--> 
 
    <input type="button" value="Test" onClick="return gettext(this);" /> 
 
    <!-- test button--> 
 
    <input type="text" name="Edit2" value="power" readonly style="border:1px solid white" /> 
 
</form>