无法将Ajax返回到HTML中

时间:2015-01-24 22:23:24

标签: javascript php jquery ajax dom

我尝试使用PHP文件处理来自Ajax请求的序列化信息。我想发回每个表单字段的值,以便javascript进一步操作(插入div)。结果未插入HTML。当我提醒结果时,我得到{"return":["<p>form value for name<\/p>","<p>form value for description<\/p>"]}有任何建议吗?

编辑:使用相关HTML和修订的PHP代码更新了问题。

HTML:

<div class="col-md-4">
   <h5>Heading</h5>
   <div id="formBasicResults"></div>
</div>

使用Javascript:

.on('success.form.fv', function (e) {
  e.preventDefault();
  var $form = $(e.target);
  var bv = $form.data('formValidation');
  $.post($form.attr('action'), $form.serialize())
    .done(function (result) {
      $('#formBasicResults').html(result.responseText);
      alert(result);
  },'json');
});

PHP:

if (!isset($_SESSION)) {
  session_start();
  if (!isset($_SESSION['token'])) {
    $token = md5(uniqid(rand(), TRUE));
    $_SESSION['token'] = $token;
    $_SESSION['token_time'] = time();
  } else {
    $token = $_SESSION['token'];
  }
}

foreach($_POST as $key = > $value) {
  $temp = is_array($value) ? $value : trim($value);
  $_SESSION[$key] = $temp;
}

$expected = array(
  'name' = > 'string',
  'description' = > 'string',
);

foreach($expected AS $key) {
  if (!empty($_POST[$key])) {
    $ {$key} = $_POST[$key];
  } else {${$key} = NULL;
  }
}

foreach($expected AS $key = > $type) {
  if (empty($_POST[$key])) {
    $ {$key} = NULL;
    continue;
  }
  if (!isset($ {
    $key})) {
    $ {$key} = NULL;
  }
}
function safe( $value ) {
htmlentities( $value, ENT_QUOTES, 'utf-8' );
return ($value);
}

$name = $_POST['name'];
$description = $_POST['description'];

$return['result']=array();
if(!empty($name)){$return['result'][]= '<p>' . safe($name) . '</p>';}
if(!empty($description)){$return['result'][]= '<p>' . safe($description) . '</p>';}
echo json_encode($return); 

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

$('#formBasicResults').html(result['return'][0]); 

$('#formBasicResults').html(result['return'][1]);

答案 1 :(得分:0)

而不是:

if ($_POST['token'] == $_SESSION['token']) 
{$return['return']=array();
if(!empty($_POST['name'])){$return['return'][] = '<p>' . htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8') . '</p>'; 
if(!empty($_POST['description'])){$return['return'][] = '<p>' . htmlentities($_POST['description'], ENT_QUOTES, 'UTF-8') . '</p>';}
echo json_encode($return); }}

这样做:

$return['responseText']='';
if ($_POST['token'] == $_SESSION['token']) 
{

if(!empty($_POST['name'])){

$return['responseText'] .= '<p>' . htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8') . '</p>'; 

if(!empty($_POST['description'])){

$return['responseText'] .= '<p>' . htmlentities($_POST['description'], ENT_QUOTES, 'UTF-8') . '</p>';}

}
}
echo json_encode($return);