后端传string类型,前端使用ajax如何接受

227 篇文章 1 订阅
47 篇文章 1 订阅

下面是接受json格式:

$.ajax({
            type: 'POST',
            url: '/my/url',
            data: data,
            dataType: "json",
          });

将dataType设置为 text即可

$.ajax({
            type: 'POST',
            url: '/my/url',
            data: data,
            dataType: "text",
          });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
后端Java中接收前端Ajax发送的JSON数据,可以通过以下步骤进行实现: 1. 在前端使用JavaScript编写Ajax请求并将数据以JSON格式发送到后端Java。 ```javascript var jsonData = { "name": "John", "age": 30, "city": "New York" }; $.ajax({ type: "POST", url: "your-java-api-url", contentType: "application/json; charset=utf-8", dataType: "json", data: JSON.stringify(jsonData), success: function(response){ console.log(response); }, error: function(error){ console.log(error); } }); ``` 2. 在后端Java中使用HttpServletRequest对象获取JSON数据并解析。 ```java import org.json.JSONObject; @WebServlet("/your-java-api-url") public class YourServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringBuilder sb = new StringBuilder(); String line; while ((line = request.getReader().readLine()) != null) { sb.append(line); } JSONObject jsonObject = new JSONObject(sb.toString()); String name = jsonObject.getString("name"); int age = jsonObject.getInt("age"); String city = jsonObject.getString("city"); // Do something with the data } } ``` 在上面的代码中,我们首先获得了HttpServletRequest对象,然后通过该对象的getReader方法获取JSON数据。接着,我们使用JSONObject类解析JSON数据并获取数据中的各个属性值,最后可以对数据进行相应的处理和操作。 需要注意的是,由于使用了request.getReader()方法获取JSON数据,因此需要在前端Ajax请求中设置contentType为"application/json; charset=utf-8",以确保数据以JSON格式发送到后端Java。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值