在AMP中如何检查响应是否为空?需验证表单提交成功后的event.response.redirect
Hey there! Let's break down how to address your two AMP form questions clearly.
1. Check for event.response.redirect on Submit-Success
Your current form uses AMP.navigateTo directly when the submit succeeds, but we can add a conditional check to only run the navigation if redirect exists in the response. Here's how to modify your form:
<form class="proceed__form" id="proceed__form" method="post" action-xhr="@addtocartlink" target="_top" on="submit-success: if(event.response.redirect) { AMP.navigateTo(url: event.response.redirect); } else { // Add your fallback logic here (e.g., show a message to the user) AMP.setState({ cartStatus: 'Item added successfully, but no redirect URL was provided.' }); }"> <input type="submit" style="font-size:16px;" value="Add To Cart" /> <!-- Optional: Display status message --> <p [text]="cartStatus" class="status-message"></p> </form>
What's happening here:
- We wrap the
AMP.navigateTocall in anifstatement that checks ifevent.response.redirectexists and has a valid value. - If the redirect URL isn't present, we use
AMP.setStateto update a state variable, which can then display a fallback message to the user (you can adjust this logic to fit your needs, like showing an alert or updating other UI elements).
2. Check if the Response is Empty
In AMP, you can check for empty responses by verifying if event.response exists and whether it contains any meaningful data. There are two common scenarios to handle:
Scenario 1: No response object at all (null/undefined)
If the server returns no response, event.response will be null or undefined. You can check this with a simple negation:
on="submit-success: if(!event.response) { AMP.setState({ errorMessage: 'No response received from the server.' }); } else { // Proceed with normal response handling }"
Scenario 2: Response exists but is an empty object
Sometimes the server might return an empty JSON object ({}). To handle this, combine the check with Object.keys() to see if there are any properties in the response:
on="submit-success: if(!event.response || Object.keys(event.response).length === 0) { AMP.setState({ errorMessage: 'Server returned an empty response.' }); } else { // Handle non-empty response if(event.response.redirect) { AMP.navigateTo(url: event.response.redirect); } }"
Key Notes:
- AMP's event handling supports basic JavaScript-like expressions, but avoid complex functions or loops—stick to simple conditionals and AMP-provided methods like
AMP.setStateorAMP.navigateTo. - Always test your form with different server responses to ensure your fallback logic works as expected.
内容的提问来源于stack exchange,提问作者Maulik Patel

