成功时将数据传递给ajax调用

时间:2016-05-26 13:17:57

标签: javascript php jquery ajax

我想将json_encode()函数中的数据传递给jquery。并且在成功时我想重新加载特定的div。

触发:

<a id="js-delete-file" href="#" data-url="<?php echo site_url('document_items/remove/'. $value['id'].'/'. $value['filename']) ?>">Remove</a>

PHP:

public function remove ($id=null, $filename) {

    $dir = "_resources/docs/";
    if ($this->doc_item->remove($id)) {
        unlink($dir.$filename);
        $status = 'success';
        $msg = 'File successfully deleted';
    } else {
        $status = 'error';
        $msg = 'Something went wrong when deleting the file, please try again';
      }

      echo json_encode(array('status' => $status, 'msg' => $msg));
  }

JQUERY:

$('#js-delete-file').click(function(e){

    var url = $(this).attr('data-url');
    $.ajax({
      type: 'POST',
      url: url,
      success: function(result) {
        $('#uploaded-files').html(result);
      },
    });
  });

点击按钮后,它会给我{"status":"success","msg":"File successfully deleted"}而不是实际的html。

2 个答案:

答案 0 :(得分:2)

使用param dataType访问字段状态

$.ajax({
      type: 'POST',
      url: url,
      dataType: "json",
      success: function(result) {
        if (result.status == 'success') {
          $('#uploaded-files').html(result.msg);
        }
      }
    });

答案 1 :(得分:0)

试试这个

$('#js-delete-file').click(function(e){

    var url = $(this).attr('data-url');
    $.ajax({
      type: 'POST',
      url: url,
      success: function(result) {
         var data = JSON.parse(result);
         $('#uploaded-files').html(data.msg);
      },
    });
});