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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀