CSV 파일을 가져 와서 JSON으로 구문 분석 한 다음 REST API를 사용하여 BigCommerce로 전송하는 방법을 만들려고합니다. 처음에는 Javascript를 사용하여 모든 작업을 수행했으며 BigCommerce에 실제로 연결될 때까지 데이터를 처리했습니다. BigCommerce는 CORS를 허용하지 않으므로 서버에서 401 응답을 받고 실제로 전송 된 데이터는 없습니다. 이 때문에 PHP로 전환하려고했지만 특정 JSON 객체를 가져올 수있는 것은 자바 스크립트보다 훨씬 어렵습니다. 필자가 생각해 낸 해결책은 자바 스크립트로 데이터를 파싱하고 PHP 스크립트와 PHP 스크립트에 라인별로 전송 한 다음 BigCommerce에 연결하여 나를 보내 주면된다.AJAX에서 PHP로 JSON을 전송하는 스크립트
먼저 가능한가요? 여기
내 자바 스크립트 코드의 일부입니다 :$(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과 아빠 코드의 중간에 내가 + 1 뭔가 이상한해야 할 일을했을 알 수 있지만, 그 때문에이었다 단계 기능에서 for 루프를 수행 할 수 없습니다.
$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)
내가 특히 AJAX를 통해 그것에 통과 값을 PHP와 가장 경험이 해달라고, 그래서 어떤 도움이 좋을 것 :
내 PHP는 기본 컬 기능입니다. 필자는 파일간에 값을 전달하는 것이 실제로 어떻게 작동하는지, 어떻게이 데이터를 프로그래밍 방식으로 PHP에 전송할 수 있는지 명확하지 않습니다.
감사합니다.
자바 스크립트에서 csv 파일을 읽는 대신 PHP에 업로드하지 않는 것이 좋습니다. 그런 다음 php가 CURL을 통해 API를 읽고, 구문 분석하고 호출하게할까요? – Jeet
PHP 함수 json_encode는 데이터를 올바르게 인코딩하지만 하나의 JSON 객체에 액세스 할 수 없어 BigCommerce API로 전송합니다. 이는 각 항목의 ID가 변경되기 때문에 중요합니다. – BMitrano825
'json_encode'는 배열을'JSON' 문자열로 변환합니다. 'json' 문자열이'json' 객체를'{}'로 바꾸지 않는 경우. 그런 다음 JSON_FORCE_OBJECT를 두 번째 매개 변수로 'json_encode'에 전달합니다. 아마도이게 당신이 찾고있는 것일까요? – Jeet