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 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办