如何使用ajax将关联数组传递给PHP文件

时间:2016-06-21 20:06:37

标签: php jquery ajax

我创建了一个像这样的关联数组

HeaderArray["BillNo"] = ["BillNo", BillNo];
HeaderArray["CustomerId"] = ["CustomerId", CusId];
HeaderArray["Date"] = ["CustomerId", "03/11/1995"];

现在我正在尝试将此数组传递给PHP文件。

$.ajax({
    type: 'POST',
    url: 'Resource/Start.php',
    data: { HeaderDetails: HeaderArray },
    success: function (Data) {                                      
        console.log(Data);                          
    },
});

php文件

if (!isset($_POST['HeaderDetails'])) {
    echo 'HeaderDetails is not set';

} else {
    echo 'HeaderDetails Set';
}

在控制台中,我总是将输出设为HeaderDetails not set

2 个答案:

答案 0 :(得分:0)

尝试

  NSString *urlString = @"http://www.example.com?a=%7B1%2B2%7D";
  NSURLComponents *components = [NSURLComponents componentsWithString:urlString];
  NSLog(@"%@",components);
  // <NSURLComponents 0x7ffc42c19d40> {scheme = http, user = (null), password = (null), host = www.example.com, 
  // port = (null), path = , query = a=%7B1%2B2%7D, fragment = (null)}
  NSURLQueryItem *queryItem = [NSURLQueryItem queryItemWithName:@"hl" value:@"en-us"];
  components.queryItems = [components.queryItems arrayByAddingObject:queryItem];
  NSLog(@"%@",components);
  // <NSURLComponents 0x7ffc42c19d40> {scheme = http, user = (null), password = (null), host = www.example.com, 
  // port = (null), path = , query = a=%7B1+2%7D&hl=en-us, fragment = (null)}

答案 1 :(得分:0)

你缺少的是ajax dataType(text,json,xml)在我们的例子中我们使用text作为print_r($ _ POST)将返回一个不是json格式化的数组。 其次没有HeaderArray的声明,在这种情况下类型为object。所以,

尝试:

<form method="POST">
        <input type="submit" value="Send">
    </form>
    <script>
        $(function(){
            $("form").submit(function(event){
                event.preventDefault();
                var HeaderArray = {};
                HeaderArray["BillNo"] = ["BillNo", "12"];
                HeaderArray["CustomerId"] = ["CustomerId", "12"];
                HeaderArray["Date"] = ["CustomerId", "03/11/1995"];
                $.ajax({
                    url:"backend/yourHandler.php",
                    type:"POST",
                    dataType:"text",
                    data:{ HeaderArray : HeaderArray },
                    success:function(result){

                        console.log(result);
                    },
                    error:function(err,status,xhr){
                        console.log(err);
                    }
                });
                return false;

            });
        });
    </script>

// backend / yourHandler.php

<?PHP print_r($_POST); ?>