1

i've been playing around w/ these things and it seems that the callback function has only one response variable..

$.post(link, $("#form").serializeArray(), sendFormResponse);

where sendFormResponse function does the magic ...

however i have only 1 variable (response) to play with..

i needed at least 2

if i could get this .post method to return 2 variables: 1) status = (ok,error,adjust, etc) 2) statusMessage (or response) = (more strings)

both of w/c are generated from php side, that would be super.. coz i can evaluate what to do depending on my php's responses..

4

3 回答 3

3

You should be looking at data in the success method. Usually I would setup a standard response json object which I can validate myself.

$.post('ajax/test.php', function(response) {
  if (response.success) {
      alert(response.data.key1);
      // will display "value1"
  } else {
      alert(response.errorText);
  }
});

test.php

<?php
// so ajax client can interpret content appropriately
header('Content-Type: application/json');

// hide all php notices/warnings/errors 
// (you really should be logging them)
// ** Any text other than the json encoded string
// will break the clients parsing abilities **
ini_set('display_errors', false);


$response = array(
    "success" => true,
    "errorText" => "",
    "data" => array(
        "key1" => "value1"
    )
);

echo json_encode($response, JSON_FORCE_OBJECT);
?>
于 2013-01-12T15:30:10.093 回答
2

传递给回调(或在响应中返回)的参数可以是一个对象,它可以有无限的属性,也可以是一个包含多个元素的数组。

于 2013-01-12T15:18:50.650 回答
2

从您的 PHP 发送一个 JSON 编码的数组

echo json_encode(array('success' => 'ok', 'data1' => $data1, 'data2' => $data2)); //etc.

然后,您可以在 Javascript 中引用成功标志和数据。

$.post(link, $("#form").serializeArray(), function(data) {
   if (data.success == 'ok') {
       alert('data1 = ' + data.data1);
   } 
   else {
      alert (data.error);
   }
});
于 2013-01-12T15:22:57.547 回答