简体   繁体   English

将JSON对象传递给PHP脚本

[英]Passing JSON object to PHP script

I am trying to pass a JSON object that looks similar to this: 我正在尝试传递一个看起来与此相似的JSON对象:

 {"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]}

Just a note: In the sizeTypes, there are a total of about 58 items in the array. 请注意:在sizeTypes中,数组中总共约有58个项目。

When the user clicks the submit button, I need to be able to send the object to a PHP script to run an UPDATE query. 当用户单击“提交”按钮时,我需要能够将对象发送到PHP脚本以运行UPDATE查询。 Here is the javascript that should be sending the JSON to the PHP script: 这是应该将JSON发送到PHP脚本的javascript:

 $('#addNewSubmit').click(function()
 {
   var payload = {
     name: $('#addservice').val();
     sizeTypes: []
   };

   $('input.size_types[type=text]').each(function(){
     payload.sizeTypes.push({
       id: $(this).attr('id'),
       value: $(this).val()
      });
   });

   $.ajax({
     type: 'POST',
     url: 'api/editService.php',
     data: {service: payload},
     dataType: 'json',
     success: function(msh){
       console.log('success');
     },
     error: function(msg){
       console.log('fail');
     }
   });
 });

Using the above click function, I am trying to send the object over to php script below, which is in api/editService.php: 使用上面的单击功能,我试图将对象发送到下面的api / editService.php中的php脚本:

 <?php
 if(isset($_POST['service']))
 {
   $json = json_decode($_POST['service'], true);

   echo $json["service"]["name"] . "<br />";

   foreach ($json["service"]["sizeTypes"] as $key => $value){
     echo $value["value"] . "<br />";
   }
 }
 else
 {
   echo "Nooooooob";
 }
 ?>

I do not have the UPDATE query in place yet because I am not even sure if I am passing the JSON correctly. 我还没有UPDATE查询,因为我不确定我是否正确传递了JSON。 In the javascript click function, you see the SUCCESS and ERROR functions. 在javascript click函数中,您将看到SUCCESS和ERROR函数。 All I am producing is the ERROR function in Chrome's console. 我所产生的只是Chrome控制台中的ERROR函数。

I am not sure where the error lies, in the JavaScript or the PHP. 我不确定错误在哪里,是JavaScript还是PHP。

Why can I only produce the error function in the AJAX post? 为什么我只能在AJAX帖子中产生错误函数?

Edit 编辑

I removed the dataType in the ajax call, and added JSON.stringify to data: 我在ajax调用中删除了dataType,并向数据添加了JSON.stringify:

 $.ajax({
   type: 'POST',
   url: 'api/editService.php',
   data: {servce: JSON.stringify(payload)},
   success: function(msg){
     console.log('success');
   },
   error: function(msg){
     console.log('fail'), msg);
   }
 });

In the PHP script, I tried this: 在PHP脚本中,我尝试了以下操作:

 if(isset($_POST['service'))
 {
   $json = json_decode($_POST['service'], true);

   foreach ($json["service"]["sizeTypes"] as $key => $value){
     $insert = mysqli_query($dbc, "INSERT INTO table (COLUMN, COLUMN, COLUMN) VALUES (".$json["service"] . ", " . "$value["id"] . ", " . $value["value"]")");
   }
 }
 else
 {
   echo "noooooob";
 }

With this update, I am able to get the success message to fire, but that's pretty much it. 通过此更新,我能够激发成功消息,但仅此而已。 I cannot get the query to run. 我无法运行查询。

没有看到错误,我怀疑错误是因为ajax期望使用json(dataType:'json',),但是您在php中回显了html

Try to change 尝试改变

 error: function(msg){
   console.log('fail');
 }

to

 error: function(msg){
   console.log(msg);
 }

There might be some php error or syntax issue and you should be able to see it there. 可能存在php错误或语法问题,您应该可以在此处看到。

Also try to debug your php script step by step by adding something like 也可以尝试通过添加类似的步骤逐步调试php脚本

echo "still works";die;

on the beginning of php script and moving it down till it'll cause error, then you'll know where the error is. 在php脚本的开头并将其向下移动直到将导致错误,然后您将知道错误在哪里。

Also if you're expecting JSON (and you are - dataType: 'json' in js , don't echo any HTML in your php. 另外,如果您期望使用JSON(并且在js中为dataType: 'json' ,请不要在PHP中回显任何HTML。

As you are sending an object in your service key, you probably have a multi-dimensional array in $_POST['service'] . 当您在service密钥中发送对象时,您可能在$_POST['service']有一个多维数组。

If you want to send a string, you should convert the object to json: 如果要发送字符串,则应将对象转换为json:

data: {service: JSON.stringify(payload)},

Now you can decode it like you are doing in php. 现在,您可以像在php中一样对其进行解码。

Also note that you can only send json back from php if you set the dataType to json . 另请注意,如果将dataType设置为json ,则只能从php发送回json Anything other than valid json will have you end up in the error handler. 除了有效的json之外的任何内容都将使您最终进入error处理程序。

Example how to handle a JSON response from editService.php . 示例如何处理来自editService.phpJSON响应。 Typically, the editService.php script will be the worker and will handle whatever it is you need done. 通常, editService.php脚本将成为工作程序 ,并将处理您需要完成的所有操作。 It will (typically) send a simple response back to the success method (consider updating your $.ajax to use the latest methods, eg. $.done , etc). 它将(典型值)发送一个简单的响应返回success方法(考虑更新$.ajax用最新的方法,如: $.done等)。 From there you handle the responses appropriately. 从那里您可以适当地处理响应。

$.ajax({
    method: 'POST',
    url: '/api/editService.php',
    data: { service: payload },
    dataType: 'json'
})
 .done(function(msh) {
    if (msh.success) {
        console.log('success');
    }
    else {
        console.log('failed');
    }
})
 .fail(function(msg) {
    console.log('fail');
});

Example /editService.php and how to work with JSON via $.ajax 示例/editService.php以及如何通过$.ajax使用JSON

<?php
$response = [];
if ( isset($_POST['service']) ) {
    // do your stuff; DO NOT output (echo) anything here, this is simply logic
    // ... do some more stuff

    // if everything has satisfied, send response back
    $response['success'] = true;

    // else, if this logic fails, send that response back
    $response['success'] = false;
}
else {
    // initial condition failed
    $response['success'] = false;
}
echo json_encode($response);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM