2

我正在开发一个 php 应用程序,现在我必须构建一个接口来在 jquery 和 php 之间进行通信。我已经有一个工作控制器/动作。如果我需要在请求中将数组发送到 php,那么与 jQuery 进行通信的最佳方式是什么。

示例:完成请求所需的数据:

$request_data = array 
(
  'key1' => 'value1',
  'list1' => array
  (
    'listkey1' => 'listvalue1',

  )
)

我应该以不同的方式发送它作为“正常”的后请求,还是更容易发送一个用 json 编码的数组的后变量?($post_json="{key: value....})

重点是在 jquery 中的轻松集成

编辑:这不是将数据传递给客户端,而是将数组从客户端传递给 php-script

4

2 回答 2

3

使用 phps json_encode() 生成响应,并在客户端使用 jquery 读取它?

$.getJSON('youpage.php', function(data) {
  $.each(data, function(key, value) {
    alert(key + '=>' + value);
  });
}

http://php.net/manual/en/function.json-encode.php

更新

in regards to communication the other way, from the client to php. It all depends on the task at hand really. If the data in the drop down purely depend on the entries on the form, and they are otherwise stateless. Then,the best route will depends on your backend code, you could do a ajax post, with the individual variables, or concatenate them into one variable before sending, and then splitting them up on the backend. Or, as you say, you could create a json string and then use json_decode on the backend.

Which route is fit for purpose depends on many factors, and I dont think there is a right or wrong error.

Personally, I would generate a AJAX post request (im not a php coder though) to the backend, and then process the request object directly. You still would need to process a data structure, so why add the overhead/extra-step of deserializing json from the request.

于 2012-09-25T21:01:00.700 回答
1

你可以使用jquery post

$.post('url', data, function(data) {
  console.log(data);
});

您可以访问 php 中的数据

echo $_POST['key1'];
echo $_POST['key2'];
于 2012-09-25T21:12:22.803 回答