从Servlet到Ajax到HTML的JSON - 没有错误消息

时间:2015-04-22 04:12:04

标签: jquery ajax json servlets

我刚刚完成这个项目。我有一个JSON字符串

{"data":{"id":"YPekRdk","title":null,"description":null,"datetime":1429674575,"type":"image\/png","animated":false,"width":600,"height":200,"size":85694,"views":0,"bandwidth":0,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":0,"deletehash":"AZi041RwarCFD3I","name":"","link":"http:\/\/i.imgur.com\/YPekRdk.png"},"success":true,"status":200}

我从我的servlet发送它

response.getWriter().write(new Gson().toJson(imgurImageJson));

到我的ajax

$(document).ready(function () {
    $('#button').click(function () {
        var array1 = [];

        $('#sortable2 .selectedItemImg').each(function () {
            array1.push($(this).attr('src'));
        });

        $.ajax({
            url: 'generate',
            type: 'POST',
            contentType: 'text/plain',
            dataType: 'html',
            data: array1.join('\n'),

            success: function (data) {
                $.each(JSON.parse(data), function (listID, mapData) {
                    $("#displayGeneratedURL").append("<p>" + mapData.id + "</p>");
                });
            }
        });
    });
    return false;
});

并尝试在我的jsp上查看它

#displayGeneratedURL{
            color:  white; font-family: Geneva,Tahoma,Verdana,sans-serif; font-size: 12px;
        }

<div id="displayGeneratedURL">Result should be here somewhere</div>

有了这个,我收到了一条浏览器消息:

Uncaught SyntaxError: Unexpected token <

我将我的数据类型更改为application / json和其他一些东西,并且该错误消息消失了,而不是任何事情都没有发生(作为输出到屏幕或该控制台)。

我正在使用的代码主要是从我与另一个servlet一起使用的工作代码中复制的,但是使用那个带有json字符串的Gson调用仍然是不合适/错误的,但我不知道。也可能是我在ajax中的功能完全错误。

你能看到任何错误吗?

更新:

我尝试将servlet响应更改为

response.getWriter().write(imgurImageJson);

并且数据类型为dataType: 'text/html',没有显示任何内容且没有错误消息(当数据类型仅作为文本保留时,这给出了&gt;错误)

更新:我将我的ajax功能更改为此

success: function (data) {
    alert("Hello");
}

它不会发出警告框或做任何事情

我的控制台的图像在这里

enter image description here  http://i.stack.imgur.com/IZivJ.jpg

(额外的普通链接,因为否则它变得很小)

更新:

这是我的开发者控制台POST响应

enter image description here

编辑:这是我的完整servlet代码(非常混乱):

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mainClasses;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import static jdk.nashorn.internal.objects.NativeDebug.getContext;

/**
 *
 * @author J
 */
@WebServlet(name = "ImageGenerationServlet", urlPatterns = { "/generate" })
public class ImageGenerationServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request
     *            servlet request
     * @param response
     *            servlet response
     * @throws ServletException
     *             if a servlet-specific error occurs
     * @throws IOException
     *             if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ImageGenerationServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet ImageGenerationServlet at "
                    + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed"
    // desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request
     *            servlet request
     * @param response
     *            servlet response
     * @throws ServletException
     *             if a servlet-specific error occurs
     * @throws IOException
     *             if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request
     *            servlet request
     * @param response
     *            servlet response
     * @throws ServletException
     *             if a servlet-specific error occurs
     * @throws IOException
     *             if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);

        // List imageList = Arrays.asList(request.getParameter("button"));
        //
        // System.out.println(imageList);
        //
        // ArrayList <String> imageURLs = new
        // ArrayList(Arrays.asList(imageList));
        //
        // System.out.println(imageURLs);
        // ArrayList <String> imageURLs = new
        // ArrayList(request.getParameter("button"));
        // String postResponse = request.getParameter("button");
        // ArrayList<Map> imageMap = new ArrayList<Map>();
        // String[] urls1 = postResponse.split(",");
        // ImageController.controlImage(urls1);
        List<String> imageURLs = new ArrayList<String>();
        try {
            BufferedReader reader = request.getReader();
            String line;
            do {
                line = reader.readLine();

                                if (line !=null){
                imageURLs.add(line);
                                }

            } while (line != null);
        } catch (Exception e) {
        }
        ;

        try {
            // int size = imageURLs.length();

            // Our steps are:
            // 1) Retrieve array of image srcs from our jsp via jquery and parse
            // to string array.
            // 2) Process the array in ImageController to create composite
            // image, upload to local server
            // and return local image url.
            // 3) Transfer the image to imgur by sending our local image url to
            // the imgur API.
            // Retrieve the image's new imgur url in json string.
            // 4) Parse the string so that we have just the url in json format.
            // 5) Send this back to our jsp via jquery and print to screen.
            ImageController imageController = new ImageController();

            String filePath = imageController.controlImage((ArrayList<String>) imageURLs);

                        System.out.println(filePath);

            // String generatedImageFilePath =
            // ImageController.controlImage((ArrayList<String>) imageURLs);
            // UploadController uploadController = new UploadController();
            String imgurImageJson = UploadController.getImgurContent(filePath);



//                 response.setContentType("json");
        response.setCharacterEncoding("UTF-8");

//                 response.getWriter().write("hello");
                response.getWriter().write(new Gson().toJson(imgurImageJson));

//                response.getWriter().write(new Gson().toJson(imgurImageJson));

//                        System.out.println(imgurImageJson);
//
//          Scanner file = new Scanner("imgurImageJson.json");
//          String imgurImageJsonSample = file.nextLine();
//          file.close();
//
//          JsonParser parser = new JsonParser();
//          JsonObject obj = parser.parse(imgurImageJsonSample)
//                  .getAsJsonObject();
//          String imgurl = obj.get("link").toString();
//          System.out.println(imgurl);

            // uploadedImageJson
            // 1) retrieve array of urls
            // 2) send to imagegenerationcontroller
            // 3) send to uploadcontroller
            // 4) retrieve and parse the json response to get the imgur url
            // 5) response from here to user
        } catch (Exception ex) {
            Logger.getLogger(ImageGenerationServlet.class.getName()).log(
                    Level.SEVERE, null, ex);
        }

    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

1 个答案:

答案 0 :(得分:0)

我发现我的servlet的getPost()方法正在调用我的servlet的processResquest()方法。

我有一种感觉,默认情况下会在那里生成调用,并且在我第一次创建servlet时,我忘记在几天前将其注释掉/删除它。

感谢Cerlin Boss向我展示了如何查看正在创建的实际POST响应,方法是单击浏览器开发人员控制台中的POST实例,以及Ramp