I'm just trying to spit the elements of an array into seperate input fields on a form via jquery's AJAX.
Heres my javascript code:
$('#based').change(function() {
if ($(this).val().length > 0)
{
$.ajax({
type: "POST",
url: "ajax.php",
data: "id="+$(this).val(),
success: function(data){
if (data != 'error')
{
$('#keyword').val(data[2]);
$('#keyword_slug').val(data[3]);
开发者_开发知识库 }
}
});
}
});
Heres my PHP code for 'ajax.php':
$sql = mysql_query("select * from `keywords` where `id`='".mysql_real_escape_string($_POST['id'])."'");
if (mysql_num_rows($sql) == 0)
{
echo 'error';
}
else
{
while ($row = mysql_fetch_assoc($sql))
{
foreach ($row as $k => $v)
$data[] = $v;
}
echo json_encode($data);
}
Its not working. What do I do here? I've looked into serializeArray but can't get anything to work properly.
I think you need dataType: 'json'
if you are expecting JSON back.
Otherwise jQuery has to guess, and if you are not sending the Content Type application/json
, it may guess wrong.
精彩评论