如何通过AJAX响应正确地将数组传递给JSON,当前响应是否为空对象?

时间:2016-10-26 17:23:09

标签: javascript php jquery json ajax

我正在通过AJAX响应将数组传递给JSON。在登录控制台时,回复是一个空对象。如果传递一个对象就好了。

我是否正确地认为我需要.each()来分离数组。我试过这个,但没有运气。

以下是服务器端JSON响应创建:

$answers = answers::where('question_id', $question_id);

// Response
if ($request->ajax())
{
  // JSON creation
  return Array(
     'enquiry' => $enquiry_id,
     'question_title' => $question_title,
     'answers' => $answers,
     'q' => $q

  );
}
Response::json([ 'enquiry' => $enquiry_id, 'question_title' => $question_title, 'q' => $q, 'answers' => $answers]);

}

客户端响应是.done()

的一部分
.done(function(response){
    console.log("Done!");
    $('#myModal').modal('show');
    var enquiry_number = response.enquiry;
    var question_title = response.question_title;
    var answers = response.answers;
    console.log(question_title);
    console.log(answers);
    $('#myModal_title').html(response.question_title);
 })

整个AJAX

$('#continue_btn').on('click', function () {

    var form = $("#form_1"); // or $("form"), or any selector matching an element containing your input fields
    var app = $("[name='appliance']", form).val();
    var a = $('#form_1').serialize();
    var url = $('#form_1').attr('action');
    var type = $('#form_1').attr('method');
    console.log(a);
    $('#form_1').submit(function(event) {

        event.preventDefault();
        var formElem = $(event.currentTarget);

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        }
                    });

        $.ajax({
                type        : type,
                url         : url,
                data        : a,
                dataType    : 'json'
              })
              .done(function(response){
                  console.log("Done!");
                  $('#myModal').modal('show');
                  var enquiry_number = response.enquiry;
                  var q = response.q;
                  var question_title = response.question_title;
                  var answer = response.answers;
                  console.log(q);
                  console.log(question_title);
                  console.log(answer);
                  $('#myModal_title').html(response.question_title);
              })
              .fail(function(jqXHR, textStatus, errorThrown){
                  console.log("Fail!", jqXHR, textStatus, errorThrown);
              });
      });
      $('#form_1').submit();
});

RESPONSE

{"enquiry":65,"question_title":"Washing Machine Diagnosis","answers":{},"q":{"id":1,"appliance_id":1,"question":"Washing Machine Diagnosis","created_at":null,"updated_at":null}}

0 个答案:

没有答案