gpt4 book ai didi

JavaScript、JSP 和 JSON 不适用于 POST

转载 作者:行者123 更新时间:2023-12-02 12:45:58 25 4
gpt4 key购买 nike

我正在尝试创建一个客户端-服务器应用程序,我从客户端通过 JSON 对象向服务器发送请求以进行注册。问题是我应该得到另一个带有“OK”字段(实际上正在发送)的 JSON,但由于某种原因,客户端继续使用 .fail 函数而不是 .done 一(抱歉,如果某些使用的术语不是很准确,我是新手)。

所以我将这是我的代码,以便您可以检查是否有任何错误导致此问题:

客户端JS:

define(['ojs/ojcore', 'knockout', 'jquery', 'appController', 'jquery', 'ojs/ojknockout', 'ojs/ojinputtext'],
function(oj, ko, $, app) {

function RegistrarseViewModel() {
var self = this;
this.email = ko.observable();
this.pwd1 = ko.observable();
this.pwd2 = ko.observable();
this.registrar = function(){
alert("Se ha mandado el registro");
var p = {tipo:"Registrarse",email: this.email(), pwd1:this.pwd1(), pwd2:this.pwd2()};
$.ajax({
type:"POST",
url:"http://localhost:8080/ServidorWeb/Registrarse.jsp",
data: "p=" + JSON.stringify(p)
}).done(function(data, textStatus, jqXHR){
alert("Comprobando tipo");
if (data.tipo == "OK"){
//window.location="index.html?root=juegos"
sessionStorage.jugador=self.email();
app.router.go("login");
alert("Registro correcto");
}else
alert(respuesta.texto)
}).fail(function() {
alert("Sorry. Server unavailable. lol ");
});
}

this.cancelar = function(){
app.router.go("login");
}
}
return new RegistrarseViewModel();
}
);

服务器 JSP:

<%@ page language="java" contentType="application/json ; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import= "org.json.*,dominio.Manager"%>
<%
String p = request.getParameter("p");
JSONObject resultado=new JSONObject();
try{

JSONObject jso= new JSONObject(p);
if(!jso.getString("tipo").equals("Registrarse")){
resultado.put("tipo","NOK");
resultado.put("texto","Mensaje inesperado");
}else{
String email=jso.getString("email");
String pwd1=jso.getString("pwd1");
String pwd2=jso.getString("pwd2");
Manager.get().registrarse(email,pwd1,pwd2);
resultado.put("tipo","OK");
resultado.put("texto","Te has registrado con el email " + email);
}
}
catch(Exception e){
resultado.put("tipo","NOK");
resultado.put("texto","Mensaje Inesperadoo");
}
%>

<%=resultado.toString()%>

执行Manager.get().registrarse(email,pwd1,pwd2);(这是注册到MongoDB的逻辑)后,它只是继续resultado.put( "tipo","OK"); 行,这意味着问题不在那里。

此外,如果我发送请求http://localhost:8080/ServidorWeb/Registrarse.jsp?p=%7Btipo:%22Registrarse%22,email:%2233%22,pwd1:%2220%22, pwd2:%2220%22%7D 从 Google Chrome 等浏览器中打印:{"texto":"Te has registrado con el email 33","tipo":"OK"} 但从真正的客户端它不会进入 .done 函数,我不知道为什么。

我真的希望你能帮助我。

提前致谢。

编辑1:添加了来自浏览器控制台的服务器响应 IMAGE

最佳答案

好吧,我终于解决了这个问题。

我必须在 .jsp 的开头添加这一行,这是 TomCat 的一个问题,它有 2 台机器,如果没有这一行,由于安全原因,它似乎不允许不同机器之间进行通信。

response.setHeader("Access-Control-Allow-Origin", "*");

关于JavaScript、JSP 和 JSON 不适用于 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44783254/

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