JQuery:使用ajax响应填充textarea

时间:2013-03-28 13:47:02

标签: jquery populate

我有一个动态创建的下拉列表,其中我可以从MySQL数据库中选择新闻简报。需要注意的是,当我选择一个时事通讯时,数据库中的内容会被插入到textarea中。

下拉列表如下:

<?php
    echo "<select id=\"NieuwsbriefSelect\" name=\"show\">"; 
    echo "<option size =30 selected>Select</option>";
    if(mysql_num_rows($sql_result)) 
    { 
    while($row = mysql_fetch_assoc($sql_result)) 
    { 
    echo "<option value=\"$row[Titel]\">$row[Titel]</option>"; 
    } 

    } 
    else {
    echo "<option>No Names Present</option>";  
    } 
?>

jquery是这样的:

<script>
// variable to hold request
var request;
$(document).ready(function() {

$('#NieuwsbriefSelect').change(function() { 
//send Ajax call to get new contents 
var selected_text = $(this).val(); 
// setup some local variables 
var $form = $("#myForm"); 
// let's select and cache all the fields 
var $inputs = $form.find("input, select, button, textarea"); 
// serialize the data in the form 
var serializedData = $form.serialize(); 

alert(serializedData); 

// fire off the request to /get_my_contents.php 
request = $.ajax({ 
url: "/get_my_contents.php", 
type: "GET", 
data: serializedData 
}); 

alert("ajax call done"); 

// callback handler that will be called on success 
request.done(function (response, textStatus, jqXHR){ 
//populate the TextArea 
alert(response); 
$("textarea[name='content']").html(response); 
}); 



});

});
</script>

get_my_contents.php:

<?php 
$title = $_REQUEST["show"]; 
mysql_connect('localhost','root','root'); 
mysql_select_db('NAW') or die (mysql_error()); 
$strSQL = "SELECT Content from NAW.Mail where Titel = '$title' "; 
$sql_result = mysql_query($strSQL); 

$row = mysql_fetch_assoc($sql_result); 

print urldecode($row["Content"]); 
?>

所以它应该做的是将响应添加到textarea中。然而问题是ajax请求似乎没有做任何事情。当我运行此选项并从下拉列表中选择一个时事通讯时,我将获得前2个警报,但之后它什么也没做。我还要提到我基本上没有使用Jquery的经验,但有人建议我应该使用它并帮助我像当前状态一样。如果有人能够看到什么是错的或建议采用另一种方式,那就太棒了!

注意: 的 我知道我不应该使用mysql_ *,稍后我会更改为PDO!

3 个答案:

答案 0 :(得分:0)

我不确定,如果这是一个问题,但我会重写这样的代码:

request = $.ajax({ 
url: "/get_my_contents.php", 
type: "GET", 
data: serializedData
success: function(data)
    {
    //populate the TextArea 
    alert(data);
    $("textarea[name='content']").html(data); 
    }
}); 

答案 1 :(得分:0)

var myTextareaVal = $('#message-textarea').val();

$.ajax({                                       
      type: "GET",
      url: "myPhpFile.php",           
      data: "text=" + myTextareaVal,           
      cache: false,
      dataType: "html",           
      success: function(data) {   
            $('.modal_content').find('.message:last').before(data);
      }
}); 

答案 2 :(得分:0)

'数据'可能有换行符

$("textarea[name='content']").html(data); 

=

$("textarea[name='content']").html('line number1
line number2

line number3 with a previous blank line');

换行导致js错误

你只需修复换行符。

相关问题