可以用jQuery的load,post,get方法接收一个var=value的响应



我一直在玩w/这些事情,似乎回调函数只有一个响应变量。

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

然而,我只有一个变量(响应)来玩…

我至少需要2个

如果我能得到这个。post方法返回2个变量:状态= (ok,error,adjust等)2) statusMessage(或response) =(更多字符串)

w/c都是从PHP端生成的,那将是超级…因为我可以评估什么做取决于我的php的响应..

您应该查看success方法中的数据。通常我会设置一个标准的响应json对象,我可以自己验证。

$.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);
?>

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

从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);
   }
});

最新更新