通过AJAX将JSON发送到PHP脚本(Sending JSON over AJAX to PHP script)

编程入门 行业动态 更新时间:2024-10-27 07:16:16
通过AJAX将JSON发送到PHP脚本(Sending JSON over AJAX to PHP script)

我正在尝试创建一个方法来获取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); } }); }

你会注意到我必须在papa代码中间用i = 0和i + 1做一些奇怪的事情,但这是因为我无法在step函数中执行for循环。

我的php只是基本的curl函数:

$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的最佳方式。

谢谢。

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.

最满意答案

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

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

这里$jsonObj->id是您可以通过它调用API的ID。

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.

更多推荐

本文发布于:2023-07-24 08:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1243469.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发送到   脚本   AJAX   JSON   script

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!