2013-11-09 51 views
0

我正在使用jQuery/AJAX做post请求。我试图从第一个文本框中获取输入,并将其与第二个文本框中的url结合并显示结果。例如,如果用户键入asdf,则ajax函数将生成帖子,结果将显示为http://www.example.com/sdf/。我有两个问题,正如前面提到的,我有一个ajax函数,它正在执行post,但没有结果在html中显示(它显示在firebug控制台中)。其次,我如何将输入连接到url。 Live SiteAJAX发布请求和字符串连接

<script> 
$(document).ready(function() { 
    var timer = null; 
    var dataString; 

    function submitForm() { 
     $.ajax({ 
      type: "POST", 
      url: "/concatenate/index.php", 
      data: dataString, 
      dataType: "html", 
      success: function (data) { 
       $("#result").html(data); 
      } 
     }); 
     return false 
    } 
    $("#input").on("keyup", function() { 
     clearTimeout(timer); 
     timer = setTimeout(submitForm, 40); 
     var input = $("#input").val(); 
     dataString = { input : input } 
    }) 
}); 
</script> 
</head> 
<body> 

<h1>Enter a word:</h1> 

<form action="create_entry.php" method="post"> 
Input: <input type="text" id="input" name="zipcode"></br> 
Concatenated Result: <input type="text" id="result" name="location" value="http//www.example.com/ /" readonly></br> 
</form> 
+0

使用$( “#结果”)VAL(数据)。而不是$(“#result”)。html(data); –

回答

2

我会建议你把参数传递submitForm而不是使用数据的全局变量。

要进行连接可以使用.data()方法存储输入的原始值,并始终抓取该值,然后将新值添加到该值。

<!-- remove extra space and "/" --> 
<input type="text" id="result" name="location" value="http//www.example.com/" readonly> 

$(document).ready(function() { 
    var timer = null; 
    /* cache $("#result") and store initial url value*/ 
    var $result=$("#result"); 
    $result.data('url',$result.val()); 

    function submitForm(input) { 
     $.ajax({ 
      type: "POST", 
      url: "/concatenate/index.php", 
      data: {input:input}, 
      dataType: "html", 
      success: function (data) { 
       /* new value from stored url and new user input*/ 
       var url=$result.data('url'), 
       newUrl= url+data; 
       /* use val() not html() */ 
       $result.val(newUrl); 
      } 
     }); 
     return false 
    } 


    $("#input").on("keyup", function() { 
     /* no point using "$("#input")" to search DOM again when already have "this"*/ 
     var input = $(this).val(); 
     clearTimeout(timer); 
     timer = setTimeout(function(){ 
      submitForm(input) ; 
     }, 40); 


    }) 
}); 
+0

什么都没有显示,在萤火虫控制台中检查,甚至没有发出发布请求。 [链接](http://webprolearner.ueuo.com/concatenate/) – user2970730

+0

确定快速修复缓存值 – charlietfl

+0

我喜欢这种方法,并作出改变,但它仍然显示整个HTML页面? – user2970730

1

应该

success: function (data) { 
    $("#result").val('http//www.example.com/'+data+'/'); 
} 
1

CHAGE这

success: function (data) { 
       $("#result").html(data); 
      } 

这个

success: function (data) { 
     $("#result").attr('value','http//www.example.com/'+data+'/'); 
} 
+0

这只是不正确的......输入有价值不innerHtml – charlietfl

+0

我的错误代码更新 – user2511140

+0

我喜欢你要去的地方,但它将整个html页面追加到结果的末尾。请参阅[链接](http://webprolearner.ueuo.com/concatenate/) – user2970730