gpt4 book ai didi

javascript - 显示对象数组中的所有值时出现问题

转载 作者:行者123 更新时间:2023-12-03 00:19:29 25 4
gpt4 key购买 nike

我正在研究使用云代码在 Parse.com 中集成 Stripe 支付,并在我的 Android 应用程序中使用 Back4App。我正在用 JavaScript 编写云代码,但在显示结帐购物车中的所有查询结果时遇到一些问题。

现在,我只是尝试检索每个 cartItem 并打印出其项目名称。但最终,当用户单击“购买”时,我尝试更新数据库中的每个商品数量。

例如:

  • 用户 1 拥有购物车商品:商品 A,数量 2,售价 10 美元,商品 B,数量 2,售价 8 美元。

  • 用户 2 拥有购物车商品:商品 A,数量 2,价格 10 美元。

  • 在 parse.com 数据库中,显示商品 A 的订单总数为 4,商品 B 的订单总数为 2。

我已经在 parse.com 中创建了数据库,并为我的应用程序编写了 Java 代码,但我无法理解如何编写云代码并循环访问每个购物车项目。

如果代码有问题,我很抱歉。我几乎是在自学如何编程,而 javascript 对我来说是全新的。如果您能指出我正确的方向,我相信我会解决剩下的问题。谢谢。

现在,在 user1 的购物车中,我有 cartItems[牛排、 curry ]。但是当我运行云代码时,它只显示 curry 而不显示牛排。我希望它显示购物车中的所有商品

我的设置方式是 CartActivity.java 中的一个按钮将数据发送到 paymentActivity.java。在 paymentActivity.java 内部是我处理云代码的地方。

CartActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

public class CartActivity extends AppCompatActivity {

ArrayList<String> myCartItems;
ArrayList<String> myCartItemQuantity;
ArrayList<String> myCartItemPrice;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);

displayCart();

}

private void displayCart() {
// recieving data from MainActivity.class
myCartItems = getIntent().getExtras().getStringArrayList("cartItems");
myCartItemQuantity = getIntent().getExtras().getStringArrayList("itemQuantities");
myCartItemPrice = getIntent().getExtras().getStringArrayList("itemPrices");

Log.i("myCart ", "items: " + String.valueOf(myCartItems) + "\n" +
"itemPrices: " + String.valueOf(myCartItemPrice) + "\n" +
"itemQuantity: " + String.valueOf(myCartItemQuantity));

LinearLayout linearLayoutVert = findViewById(R.id.linearLayout);
for (int i = 0; i < myCartItems.size(); i++) {
LinearLayout linearLayoutHor = new LinearLayout(getApplicationContext());
linearLayoutHor.setOrientation(LinearLayout.HORIZONTAL);
linearLayoutVert.addView(linearLayoutHor);

TextView itemQuantity = new TextView(getApplicationContext());
TextView item = new TextView(getApplicationContext());
TextView itemPrice = new TextView(getApplicationContext());

linearLayoutHor.addView(itemQuantity);
linearLayoutHor.addView(item);
linearLayoutHor.addView(itemPrice);

itemQuantity.setText(myCartItemQuantity.get(i));
item.setText(myCartItems.get(i));
itemPrice.setText(myCartItemPrice.get(i));

//ImageView Setup
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.ic_trash);
linearLayoutHor.addView(imageView);

}
}



public void toPaymentGateway(View view) {
Intent paymentIntent = new Intent(getApplicationContext(), paymentActivity.class);
paymentIntent.putExtra("cartItems", myCartItems);
paymentIntent.putExtra("cartItemPrice", myCartItemPrice);
paymentIntent.putExtra("cartItemQuantity", myCartItemQuantity);
startActivity(paymentIntent);
}

}

paymentActivity.java

package com.example.a1994m.doorstepsdelivery;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.parse.FunctionCallback;
import com.parse.Parse;
import com.parse.ParseCloud;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.stripe.android.Stripe;
import com.stripe.android.TokenCallback;
import com.stripe.android.model.Card;
import com.stripe.android.model.Token;

import java.util.ArrayList;
import java.util.HashMap;

import static com.example.a1994m.doorstepsdelivery.TestStripe.BACK4PAPP_API;
import static com.example.a1994m.doorstepsdelivery.TestStripe.CLIENT_KEY;

public class paymentActivity extends AppCompatActivity {

ArrayList<String> myCartItems;
ArrayList<String> myCartItemQuantity;
ArrayList<String> myCartItemPrice ;
ParseUser currentUser = ParseUser.getCurrentUser();

public static final String PUBLISHABLE_KEY = "_________";
public static final String APPLICATION_ID = "____________";
public static final String CLIENT_KEY = "_____________";
public static final String BACK4PAPP_API = "https://parseapi.back4app.com/";
private Card card;
private ProgressDialog progress;
private Button purchase;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);

// Connect to Your Back4app Account
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId(APPLICATION_ID)
.clientKey(CLIENT_KEY)
.server(BACK4PAPP_API).build());
Parse.setLogLevel(Parse.LOG_LEVEL_VERBOSE);

// Create a demo test credit Card
// You can pass the payment form data to create a Real Credit card
// But you need to implement youself.

card = new Card(
"344776435490016", //card number
05, //expMonth
2021,//expYear
"216"//cvc
);
progress = new ProgressDialog(this);
purchase = (Button) findViewById(R.id.purchase);
purchase.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// buy();
charge();
Log.i("redirecting...", "BUTTON HAS BEEN CLICKED");
}
});

// recieving data from CartActivity.class
myCartItems = getIntent().getExtras().getStringArrayList("cartItems");
myCartItemQuantity = getIntent().getExtras().getStringArrayList("cartItemQuantity");
myCartItemPrice = getIntent().getExtras().getStringArrayList("cartItemPrice");

Log.i("PaymentGateItems ", "items: " + String.valueOf(myCartItems) + "\n" +
"itemPrices: " + String.valueOf(myCartItemPrice) + "\n" +
"itemQuantity: " + String.valueOf(myCartItemQuantity));
}

// public void placeOrder(View view){
//
// Intent stripeIntent = new Intent(getApplicationContext(), TestStripe.class);
// startActivity(stripeIntent);
// }

// private void buy(){
// boolean validation = card.validateCard();
// if(validation){
// startProgress("Validating Credit Card");
// new Stripe(this).createToken(
// card,
// PUBLISHABLE_KEY,
// new TokenCallback() {
// @Override
// public void onError(Exception error) {
// Log.d("Stripe",error.toString());
// }
//
// @Override
// public void onSuccess(Token token) {
// finishProgress();
// charge(token);
// }
// });
// } else if (!card.validateNumber()) {
// Log.d("Stripe","The card number that you entered is invalid");
// } else if (!card.validateExpiryDate()) {
// Log.d("Stripe","The expiration date that you entered is invalid");
// } else if (!card.validateCVC()) {
// Log.d("Stripe","The CVC code that you entered is invalid");
// } else {
// Log.d("Stripe","The card details that you entered are invalid");
// }
// }

// private void charge(Token cardToken){
// HashMap<String, Object> params = new HashMap<String, Object>();
//
// Log.i("items: ", String.valueOf(myCartItems));
//
// params.put("quantity", myCartItemQuantity);
// params.put("price", myCartItemPrice);
// params.put("ItemName", myCartItems);
//// params.put("ItemName", "Pancake");
// params.put("cardToken", cardToken.getId());
// params.put("name",currentUser.getUsername());
//// params.put("name","Dominic Wong");
// params.put("email",currentUser.getEmail());
//// params.put("email","dominwong4@gmail.com");
// params.put("address","HIHI"); // needs input from billing address on card
// params.put("zip","99999"); // needs input from billing address on card
// params.put("city_state","CA"); // needs input from billing addresss on card
// startProgress("Purchasing Item");
// ParseCloud.callFunctionInBackground("purchaseItem", params, new FunctionCallback<Object>() {
// public void done(Object response, ParseException e) {
// finishProgress();
// if (e == null) {
// Log.d("Cloud Response", "There were no exceptions! " + response.toString());
// Toast.makeText(getApplicationContext(),
// "Item Purchased Successfully ",
// Toast.LENGTH_LONG).show();
// } else {
// Log.d("Cloud Response", "Exception: " + e);
// Toast.makeText(getApplicationContext(),
// e.getMessage().toString(),
// Toast.LENGTH_LONG).show();
// }
// }
// });
// }

private void charge(){
HashMap<String, Object> params = new HashMap<String, Object>();

Log.i("items: ", String.valueOf(myCartItems));

params.put("quantity", myCartItemQuantity);
params.put("price", myCartItemPrice);
params.put("ItemName", myCartItems);
// params.put("ItemName", "Pancake");
// params.put("cardToken", cardToken.getId());
params.put("name",currentUser.getUsername());
// params.put("name","Dominic Wong");
params.put("email",currentUser.getEmail());
// params.put("email","dominwong4@gmail.com");
params.put("address","HIHI"); // needs input from billing address on card
params.put("zip","99999"); // needs input from billing address on card
params.put("city_state","CA"); // needs input from billing addresss on card
startProgress("Purchasing Item");
ParseCloud.callFunctionInBackground("purchaseItem", params, new FunctionCallback<Object>() {
public void done(Object response, ParseException e) {
finishProgress();
if (e == null) {
Log.d("Cloud Response", "There were no exceptions! " + response.toString());
Toast.makeText(getApplicationContext(),
"Item Purchased Successfully ",
Toast.LENGTH_LONG).show();
} else {
Log.d("Cloud Response", "Exception: " + e);
Toast.makeText(getApplicationContext(),
e.getMessage().toString(),
Toast.LENGTH_LONG).show();
}
}
});
}

private void startProgress(String title){
progress.setTitle(title);
progress.setMessage("Please Wait");
progress.show();
}

private void finishProgress(){
progress.dismiss();
}
}

云代码:

var Stripe = require("stripe")("sk_test_rU8GCiz0tkNB02ZbcsXP3b2a");
Parse.Cloud.define("purchaseItem", function (request, response) {
var item, order;
var total = 0;

var CartItems = request.params.ItemName;
var CartPrice = request.params.price;
var CartItemQuantity = request.params.quantity;

var cartQuery = new Parse.Query('Item');

for(var i=0; i<CartItems.length; i++){

cartQuery.equalTo('ItemName', CartItems[i]);

cartQuery.find()
.then(function (results) {
for (var result of results) {
response.success("got the items " +
result.get("ItemName"));
}
})
.catch(function (error) {
response.error("could not get the items " + error);
});
}
});

最佳答案

您应该只调用 response.success 一次。后续调用将被忽略。你可以尝试这样的事情。

cartQuery.find()
.then(function (results) {
var items = [];
for (var result of results) {
items.push(result.get("ItemName"));

}
response.success(JSON.stringify(items));
})
.catch(function (error) {
response.error("could not get the items " + error);
});

这将以数组形式响应项目。例如[“牛排”,“ curry ”]然后您应该在客户端处理这个问题。例如使用 JSONArray

关于javascript - 显示对象数组中的所有值时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54380022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com