drny60365 2016-08-08 02:36
浏览 60
已采纳

通过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.

  • 写回答

2条回答 默认 最新

  • dousa2794 2016-08-09 18:44
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同