通过AJAX将JSON发送到PHP脚本

I am attempting to create a method to take a CSV file, parse it into JSON, then send it to BigCommerce using their REST API. Initially I was going to use Javascript to do the whole thing, and everything up until actually connected to BigCommerce to PUT the data worked. BigCommerce doesn't allow CORS, resulting in a 401 response from the server and none of my data actually being sent. Because of this, I was going to switch to do it with PHP but being able to get the specific JSON object is much harder than it was with Javascript. The solution I've come up with would be for me to parse the data in Javascript, send it line by line to the PHP script and the PHP script would then connect to BigCommerce and send it for me.

First off, is this possible?

Here is some of my Javascript code:

$(document).ready(function () {
            $('[type=file]').change(function () {
                if (!("files" in this)) {
                    alert("File reading not supported in this browser");
                }
                var file = this.files && this.files[0];
                if (!file) {
                    return;
                }


                i=0;
                Papa.parse(file, {
                    delimiter: ",", // auto-detect
                    newline: "",    // auto-detect
                    header: true,
                    dynamicTyping: true,
                    preview: 0,
                    encoding: "",
                    worker: false,
                    comments: false,
                    step: function(results, parser) {
                        console.log("Row data:", results.data);
                        console.log("Row errors:", results.errors);
                        currentID = results.data[i]["id"];
                        currentResult = results.data[i];
                        sendToBC(currentID, currentResult);
                        i+1;
                    },
                    complete: function(results, file) {
                        console.log("Parsing complete:", results, file);
                        $("#parsed_JSON").css("display", "block");
                        $("#ready_btn").css("display", "block");
                        $("#select_file").css("display", "none");
                        $("#retry_btn").css("display", "block");
                    },
                    error: function(error, file) {
                        console.log("Parsing failed:", error, file);
                        alert("Parsing failed. Check file and refresh to try again.");
                    },
                    download: false,
                    skipEmptyLines: true,
                    chunk: undefined,
                    fastMode: undefined,
                    beforeFirstChunk: undefined,
                    withCredentials: undefined

                })
            });

            function sendToBC(id,data) {
                jQuery.ajax({
                    type: "PUT",
                    url: "https://store.mybigcommerce.com/api/v2/products/" + id + "/discountrules.json",
                    data: data,
                    xhrFields: {
                        withCredentials: true
                    },
                    headers: {
                        'Authorization': 'Basic ' + btoa('username:key')
                    },
                    dataType:"json",
                    async: false,

                    success: function() {
                        alert("success")
                    },
                    error: function(xhr, status, error) {
                      console.log(error);
                    }

                });
            }

You'll notice I had to do something weird with the i=0 and the i+1 in the middle of the papa code but that was because I couldn't do a for loop in the step function.

My php is just the basic curl functions:

    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $api_url );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, array ('Accept: application/json', 'Content-Length: 0') );
    curl_setopt( $ch, CURLOPT_VERBOSE, 0 );
    curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
    curl_setopt( $ch, CURLOPT_USERPWD, "username:key" );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $complete);  
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
    $response = curl_exec( $ch );
    curl_close ($ch)

I dont have the most experience with PHP especially with passing values into it through AJAX, so any help would be great. I'm not really certain how passing values between the files really works and how I can send this data to the PHP the best way programatically.

Thanks.

dongqiao1158
dongqiao1158 如果来自csv的每一行都是单独的json对象。你可以将它们组合成一个数组。
大约 4 年之前 回复
donglaogu3788
donglaogu3788 我似乎无法获得一个JSON对象。每个对象看起来像“{”id“:”77“,”min“:”1“,”max“:”6“,”price“:10}我需要能够一次抓住一个并拉然后id将对象/字符串发送到API。
大约 4 年之前 回复
dongwei6700
dongwei6700 json_encode将数组转换为JSON字符串。如果你的json字符串没有像{}那样转向json对象。然后将JSON_FORCE_OBJECT作为第二个参数传递给json_encode。可能是,这是你在找什么?
大约 4 年之前 回复
dongxin0031
dongxin0031 PHP函数json_encode正确编码数据,但我无法访问单个JSON对象将其发送到BigCommerceAPI,这很重要,因为每个项目的ID都将发生变化。
大约 4 年之前 回复
dongluan0020
dongluan0020 而不是在javascript中读取csv文件,为什么不将它上传到PHP。然后让PHP通过CURL读取,解析和调用API?
大约 4 年之前 回复

2个回答



好吧,所以我最终做的方式就是使用PHP并自己构建一个JSON字符串,并从中检索出来的值 按键排列数组。 所以我做了:</ p>

  contents [$ i] ['id'] 
</ code> </ pre>

获取id 当前项目并将其存储在变量中,并为csv的所有其他列执行该操作。 然后我构建了一个这样的字符串:</ p>

  $ jsonObject [] ='{“min”:'。$ min。',“max”:'。$ max。'  ,“type”:“'。$ type。'”,“type_value”:'。$ value。'}'; 
</ code> </ pre>

并通过API发送 使用CURL到Bigcommerce。</ p>
</ div>

展开原文

原文

Alright, so the way I ended up doing it was just using PHP and building a JSON string on my own with the values retrieved from the array by their key. So I did:

contents[$i]['id'] 

to get the id of the current item and stored it in a variable and did that for all the other columns of the csv. Then I built a string like this:

$jsonObject[] = '{"min": '.$min.',"max": '.$max.',"type": "'.$type.'","type_value": '.$value.'}';

and sent it through the API to Bigcommerce using CURL.

Considering you get an string object like {"id": "77", "min": "1", "max": "6", "price": 10}. and you want to retrieve id (77) from the JSON object.

$str = '{"id": "77", "min": "1", "max": "6", "price": 10}';
$jsonObj = json_decode($str);
$jsonObj->id; // the id.

Here $jsonObj->id is the id via which you can call your API.

dongzhao8233
dongzhao8233 是的,这基本上是我最终做的,只是自己构建了JSON字符串以发送到API。 谢谢你的帮助,你让我走上了正确的道路。
大约 4 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐