通过AJAX将JSON发送到PHP脚本

时间:2016-08-08 02:36:57

标签: javascript php json ajax bigcommerce

我正在尝试创建一个方法来获取CSV文件,将其解析为JSON,然后使用他们的REST API将其发送到BigCommerce。最初我打算使用Javascript完成整个事情,直到实际连接到BigCommerce以使数据工作的所有内容。 BigCommerce不允许使用CORS,从而导致服务器发出401响应,而我的数据实际上并未发送。因此,我打算用PHP来切换它,但是能够获得特定的JSON对象比使用Javascript更难。我提出的解决方案是让我在Javascript中解析数据,逐行将其发送到PHP脚本,然后PHP脚本将连接到BigCommerce并发送给我。

首先,这可能吗?

以下是我的一些Javascript代码:

$(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);
                    }

                });
            }

你会注意到我必须用爸爸代码中间的i = 0和i + 1做一些奇怪的事情,但那是因为我不能在步骤函数中做一个for循环

我的php只是基本的卷曲功能:

    $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)

我没有最熟悉PHP的经验,特别是通过AJAX将值传递给它,所以任何帮助都会很棒。我不确定文件之间的传递值是如何真正有效的,以及如何以编程方式将这些数据发送到PHP。

感谢。

2 个答案:

答案 0 :(得分:0)

考虑到你得到一个像{"id": "77", "min": "1", "max": "6", "price": 10}这样的字符串对象。并且您想从77对象中检索id(JSON)。

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

此处$jsonObj->id是您可以通过其调用API的ID。

答案 1 :(得分:0)

好吧,所以我最终做到这一点的方式就是使用PHP并自己构建一个JSON字符串,其中包含通过键从数组中检索到的值。所以我做了:

contents[$i]['id'] 

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

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

并使用CURL通过API将其发送到Bigcommerce。