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 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败